The 30 second answer
A String can't change after it's created; methods like concat or toUpperCase return a new String. That makes strings safe to share between threads, safe as HashMap keys, safe for things like file paths and class names, and it lets the JVM reuse literals from the string pool. When I build a string in a loop I use StringBuilder, which is mutable and fast. StringBuffer is the old synchronized version; it's rarely needed now.
<!-- level: 1 --> <!-- must_know: true -->
- The
StringJavadoc says strings are constant: their values cannot be changed after they are created, and because they are immutable they can be shared. - Why it matters: thread safety without locks, stable hash codes for map keys (
Stringcaches its hash), security for values such as file names and URLs that are checked and then used, and literal reuse through the string pool. - Cost: concatenating in a loop with
+=creates a new object on each iteration.
String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes (immutable) | No | Yes (synchronized) |
| Use | Values, keys, constants | Building strings in one thread | Legacy code shared across threads |
The StringBuilder Javadoc describes it as compatible with StringBuffer "but with no guarantee of synchronization", and recommends it in preference to StringBuffer where possible because it will be faster in most implementations.
How many objects new String("java") creates is covered in How does the String pool work, and how many objects does new String create?.
Sources (2)
- Javadoc: java.lang.Stringdocs.oracle.com
- Javadoc: java.lang.StringBuilderdocs.oracle.com