Because Java String objects are strictly immutable, every modification (concatenation, replacement, substring) creates a brand-new object on the Heap. When performing hundreds or thousands of string modifications, you must use mutable character buffers: StringBuilder or StringBuffer.
| Feature | String |
StringBuffer |
StringBuilder |
|---|---|---|---|
| Storage Type | Immutable | Mutable | Mutable |
| Thread-Safety | Yes (by immutability) | Yes (Synchronized) | No (Not thread-safe) |
| Speed / Performance | Slow on mutations | Medium (Lock overhead) | Fastest (No locks) |
| Introduced In | JDK 1.0 | JDK 1.0 | JDK 5.0 |
Observe the dramatic real-world performance difference when appending 50,000 strings in a loop:
public class StringBenchmark {
public static void main(String[] args) {
int iterations = 50_000;
// Test 1: String Concatenation (+)
long start1 = System.currentTimeMillis();
String str = "";
for (int i = 0; i < iterations; i++) {
str += i; // Disaster: Creates 50,000 intermediate Heap objects!
}
long duration1 = System.currentTimeMillis() - start1;
System.out.println("String (+) time: " + duration1 + " ms (~1,800 ms)");
// Test 2: StringBuilder (.append())
long start2 = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++) {
sb.append(i); // In-place buffer modification!
}
long duration2 = System.currentTimeMillis() - start2;
System.out.println("StringBuilder time: " + duration2 + " ms (~3 ms)");
}
}
StringBuilder sb = new StringBuilder("Veewom");
sb.append(" Java"); // "Veewom Java"
sb.insert(6, " Master"); // "Veewom Master Java"
sb.replace(0, 6, "Learn"); // "Learn Master Java"
sb.delete(5, 12); // "Learn Java"
sb.reverse(); // "avaJ nraeL"
String result = sb.toString(); // Converts back to immutable String
Exam Question: "When should a developer choose StringBuffer over StringBuilder?"
Answer: Choose StringBuffer ONLY when multiple threads are concurrently accessing and modifying the exact same string buffer instance without external locking. For 99% of modern applications (local method variables, string builders, JSON formatting), StringBuilder is the universally recommended choice because it avoids unnecessary synchronization lock overhead.
Now let us explore Java Wrapper Classes, Autoboxing, Unboxing, and the IntegerCache trap. Proceed to: Wrapper Classes & Autoboxing →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Immutable string comparison.
Monitor locks and thread-safety.
Memory optimization best practices.
Autoboxing and unboxing.