String vs StringBuilder vs StringBuffer
Compare String, StringBuilder and StringBuffer in Java: immutability, thread-safety, performance, and when to use each with clear code examples.
Expected Interview Answer
String is immutable, while StringBuilder and StringBuffer are mutable sequences of characters; StringBuilder is fast but not thread-safe, whereas StringBuffer is thread-safe because its methods are synchronized.
Use String for fixed text and when values rarely change. For heavy in-place modification such as building text in a loop, use StringBuilder, which mutates an internal char array without creating new objects each time. Choose StringBuffer only when multiple threads modify the same buffer, since its synchronized methods add overhead you do not need in single-threaded code. Since Java 5, StringBuilder is the default choice for concatenation performance.
- String: simple, safe to share, and interned for memory reuse
- StringBuilder: fast mutable building with no per-step object creation
- StringBuffer: thread-safe mutation for concurrent access
- Avoids the O(n^2) cost of repeated String concatenation in loops
- Clear performance-vs-safety trade-off to reason about
AI Mentor Explanation
A String is a printed final scorecard you cannot alter, so every correction means a whole new print. A StringBuilder is the scorer's live pencil sheet — one person rubbing out and rewriting runs quickly. A StringBuffer is that same sheet but with a rule that only one official at a time may touch it, keeping two scorers from clashing.
Step-by-Step Explanation
Step 1
Pick String for fixed text
Use String when the value is constant or changes rarely; immutability makes it safe and poolable.
Step 2
Detect heavy mutation
If you concatenate repeatedly, especially in a loop, plain String creates many throwaway objects.
Step 3
Prefer StringBuilder
In single-threaded code, use StringBuilder to append into one internal char array with no per-step allocation.
Step 4
Use StringBuffer when shared
Only when multiple threads mutate the same buffer, use StringBuffer for its synchronized methods.
Step 5
Size the buffer
Give StringBuilder/StringBuffer an initial capacity when the final length is roughly known to avoid resizing.
What Interviewer Expects
- Immutable vs mutable distinction
- Thread-safety difference between StringBuilder and StringBuffer
- Performance reasoning for loop concatenation
- When each type is the right choice
- Awareness of initial capacity and internal char array
Common Mistakes
- Saying StringBuilder is thread-safe
- Using String concatenation inside large loops
- Claiming StringBuffer is always faster than StringBuilder
- Thinking StringBuilder and StringBuffer are immutable
- Assuming synchronization in StringBuffer is free
Best Answer (HR Friendly)
“String is fixed text you cannot change, StringBuilder is a fast editable version for building text on your own, and StringBuffer is the editable version that is safe when several tasks work on it at the same time. You pick StringBuilder for speed and StringBuffer when threads share the same buffer.”
Code Example
// Inefficient: creates many temporary String objects
String result = "";
for (int i = 0; i < 5; i++) {
result += i; // new String each iteration
}
// Efficient: one mutable buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i); // mutates internal array
}
String fast = sb.toString(); // "01234"
// Thread-safe variant when a buffer is shared across threads
StringBuffer buf = new StringBuffer();
buf.append("safe"); // synchronized methodsFollow-up Questions
- Why does String concatenation in a loop have poor performance?
- How does setting an initial capacity help StringBuilder?
- Are StringBuilder methods atomic across threads?
- What does the compiler do with 'a' + 'b' + 'c' at compile time?
- When would you still choose StringBuffer over StringBuilder today?
MCQ Practice
1. Which class is mutable AND thread-safe?
StringBuffer is mutable and its methods are synchronized, making it thread-safe; StringBuilder is mutable but not synchronized.
2. Best choice for building text in a single-threaded loop?
StringBuilder mutates one internal array without per-iteration allocation and has no synchronization overhead.
3. What is the main cost of StringBuffer versus StringBuilder?
StringBuffer's synchronized methods add locking overhead that is wasted in single-threaded code.
Flash Cards
Is StringBuilder thread-safe? — No. It is mutable and fast but not synchronized; use StringBuffer when threads share a buffer.
Is StringBuffer immutable? — No. Both StringBuffer and StringBuilder are mutable; only String is immutable.
Why avoid String += in loops? — Each concatenation creates a new String, giving O(n^2) behavior and many garbage objects.
Default choice for concatenation? — StringBuilder, since Java 5 — mutable, fast, and no synchronization overhead in single-threaded code.