| String | StringBuilder | StringBuffer |
|---|---|---|
| Immutable | Mutable | Mutable |
| Thread-safe (because immutable) | Not thread-safe | Thread-safe (synchronized) |
| Slow for many changes | Fastest | Slower than StringBuilder |
String s1 = "hello"; // string pool
String s2 = "hello"; // same pool object
String s3 = new String("hello"); // new heap object
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true (same content)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.reverse()); // 43210
Q & A
-
== vs equals()?== compares references (same object?). equals() compares content. Always use equals() for strings.
-
Why is String immutable?For security (class names, URLs, passwords), string pool sharing, thread safety and caching the hashCode.