String vs StringBuilder vs StringBuffer
Fast recall
Quick revision
Core answer
Whether you understand immutability and its implications, when mutation matters for performance, and whether you know that StringBuffer's synchronization is rarely needed
Recommending StringBuffer for thread-safety without realizing that compound operations (append + append) still aren't atomic, or not knowing that the compiler converts simple string concatenation to StringBuilder internally
Mention that the Java compiler rewrites `+` concatenation to StringBuilder for single-expression concatenation, but a loop with `+` still creates O(n) intermediate Strings. Mention Java 15+ text blocks and that Java 9+ uses StringConcatFactory for even better inlining.
Interview-ready guide
Interview answer
The distinction comes down to mutability — String is immutable, StringBuilder is mutable, and StringBuffer is the synchronized but rarely-needed legacy version.
String:
- Every modification (
concat(),replace(),+) allocates a brand-new object - Immutability makes it thread-safe, poolable, and safe as a HashMap key
- The compiler rewrites single-expression
+toStringBuilder(Java 9+:StringConcatFactory)
StringBuilder:
- Mutable internal buffer — no allocations until
toString() - Use explicitly in loops:
result += rowis O(n²),sb.append(row)is O(n) - Not thread-safe — safe for single-threaded use only
StringBuffer:
- Synchronized version of StringBuilder — every method acquires a lock
- The synchronization is misleading:
buffer.append(x).append(y)acquires and releases the lock twice — another thread can interleave between them - No valid modern use case — StringBuilder is always better single-threaded
I recommend String for literals and simple concatenation, StringBuilder for building in loops, and ignoring StringBuffer.
String vs StringBuilder vs StringBuffer
Direct Answer
String is immutable — every modification creates a new object. StringBuilder is a mutable buffer optimized for single-threaded string construction. StringBuffer is identical to StringBuilder but every method is synchronized, making it thread-safe at the cost of performance. In modern code StringBuilder is nearly always the right choice for dynamic string assembly.
Common Mistakes & Pitfalls
Recommending StringBuffer for thread-safety without realizing that compound operations (append + append) still aren't atomic, or not knowing that the compiler converts simple string concatenation to StringBuilder internally
Check your understanding
Answer these without looking back at the article.
- Why is String immutable in Java?
- How does the Java compiler optimize string concatenation with +?
- What are Java text blocks and when should you use them?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.