String vs StringBuilder: What's the Difference?
Compare String and StringBuilder in Java: immutability, performance for heavy concatenation, and when to choose StringBuffer for thread-safety instead.
Expected Interview Answer
String is immutable in Java, so every apparent modification actually creates a brand-new String object, while StringBuilder is a mutable, resizable character sequence that modifies its internal buffer in place, making it far more efficient for heavy string concatenation.
Because String objects never change after creation, operations like concatenation with + inside a loop repeatedly allocate new objects and discard the old ones, creating garbage collection pressure that scales quadratically with loop size. StringBuilder instead maintains an internal char array that grows via append() calls, doubling capacity as needed, so building a large string is closer to linear time. StringBuffer is StringBuilder's older, synchronized twin, useful only when multiple threads mutate the same buffer concurrently, at the cost of synchronization overhead that StringBuilder doesn't pay. String's immutability also underlies string interning, safe use as a HashMap key, and thread-safety by default.
- String immutability guarantees safe sharing across threads
- String supports interning and pooling, saving memory for literals
- StringBuilder avoids the overhead of repeated object allocation
- StringBuilder gives near-linear performance for heavy concatenation
- StringBuffer offers a synchronized option when truly needed
AI Mentor Explanation
A String is like a printed scorecard — once printed, correcting a single run means reprinting the entire card from scratch. A StringBuilder is like a scorer's chalk board where you simply add the next ball's outcome to the existing board without erasing and rewriting everything, and StringBuffer is like that same chalk board but with a rule that only one scorer may touch it at a time.
Step-by-Step Explanation
Step 1
Understand String immutability
Every String method that appears to modify a string actually returns a new String object; the original is unchanged.
Step 2
See the cost in a loop
Concatenating with + inside a loop allocates a new String each iteration, causing O(n^2) time and GC pressure over n iterations.
Step 3
Use StringBuilder for mutation
append(), insert(), and delete() mutate an internal char array in place without creating new objects each time.
Step 4
Know when to use StringBuffer
Choose StringBuffer only if multiple threads truly mutate the same buffer concurrently; otherwise its synchronization is wasted overhead.
Step 5
Convert back when done
Call toString() on the StringBuilder once building is complete to get the final immutable String.
What Interviewer Expects
- Explains why String is immutable and what that guarantees
- Can articulate the performance cost of concatenation in a loop
- Knows StringBuilder mutates an internal buffer, avoiding reallocation
- Knows when StringBuffer's synchronization is actually warranted
- Mentions String pooling/interning as a benefit of immutability
Common Mistakes
- Believing String methods like replace() mutate the original object
- Using + concatenation inside large loops without realizing the quadratic cost
- Assuming StringBuilder is always thread-safe (it is not; StringBuffer is)
- Choosing StringBuffer by default when there's no actual multithreaded access
- Forgetting to call toString() when a String is required from a StringBuilder
Best Answer (HR Friendly)
“A String in Java never changes once created — any edit actually makes a new copy behind the scenes, which is fine for occasional use but slow if done repeatedly. StringBuilder is a more efficient tool designed specifically for building up or changing text a lot, like inside a loop, because it edits the same piece of memory instead of copying it over and over.”
Code Example
// Inefficient: creates a new String object on every iteration
String result = "";
for (int i = 0; i < 5; i++) {
result += i; // new object each time
}
System.out.println(result); // 01234
// Efficient: mutates one internal buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i); // no new object per iteration
}
System.out.println(sb.toString()); // 01234Follow-up Questions
- Why is String immutable in Java, and what benefits does that provide?
- What is the difference between StringBuilder and StringBuffer?
- How does the string pool relate to String immutability?
- What is the time complexity of repeated + concatenation in a loop?
- When would you still choose String over StringBuilder despite the performance difference?
MCQ Practice
1. What happens when you call a method like replace() on a String?
Strings are immutable, so any transformation method returns a new String instance instead of modifying the original.
2. Why is StringBuilder generally preferred over StringBuffer in single-threaded code?
StringBuffer's methods are synchronized for thread-safety, which is unnecessary overhead when only one thread accesses the buffer.
3. What is the main performance risk of concatenating strings with + inside a large loop?
Each + concatenation allocates a new String, so repeated concatenation in a loop scales poorly compared to StringBuilder.append().
Flash Cards
Is String mutable or immutable in Java? — Immutable — every transformation returns a new String object.
Why is StringBuilder faster for heavy concatenation? — It mutates one internal char array buffer instead of allocating a new object each time.
What's the difference between StringBuilder and StringBuffer? — StringBuffer's methods are synchronized for thread-safety; StringBuilder is not synchronized and is faster in single-threaded use.
Name one benefit of String immutability. — It enables safe sharing across threads and string pooling/interning to save memory.