String vs StringBuilder — When to Use Which
Fast recall
Quick revision
Core answer
String for finished text values and normal API boundaries. Use StringBuilder while assembling many pieces, especially when a result grows across a loop, then call toString(). Small + expressions are readable and handled by the compiler. A mutable builder can technically be a map key, but its identity-based equality rarely matches a content-key requirement; use the finished String instead.Whether you can identify the right tool for a given situation — not just knowing both exist, but knowing which scenario calls for which.
Using String + in loops (O(n²)) or creating a StringBuilder for a single, simple concatenation (unnecessary verbosity).
Mention that single-line + is fine because the compiler converts it to StringBuilder anyway. The actual performance difference only shows up in loops and conditional multi-part assembly.
Interview-ready guide
Interview answer
The cleanest way to frame it is known versus assembled. If you already have the text — a constant, a parameter, a return value, a map key — use String. It's immutable and exactly what every Java method signature is asking for. If you're building the text up at runtime, that's when StringBuilder earns its place.
The detail that usually separates people is what the compiler does for you. A plain "Hello, " + name + "!" on one line doesn't need a builder — the compiler already rewrites simple concatenation into a StringBuilder behind the scenes. So wrapping a single join in a manual StringBuilder is just noise.
Where it actually matters is loops. The moment a + sits inside a loop, the compiler creates a fresh builder on every iteration, and you're back to copying the whole growing string each time — the O(n²) blow-up. There you hoist one StringBuilder outside the loop and append() into it. Same story for conditional assembly, like a SQL query where you add WHERE clauses only when filters apply.
So my rule: don't reach for StringBuilder reflexively — use String for fixed values and single concatenations, and switch the moment you're appending in a loop or assembling conditionally. Build on it, call toString() once, and hand back the String.
String vs StringBuilder — When to Use Which
Direct Answer
Use String for finished text values and normal API boundaries. Use StringBuilder while assembling many pieces, especially when a result grows across a loop, then call toString(). Small + expressions are readable and handled by the compiler. A mutable builder can technically be a map key, but its identity-based equality rarely matches a content-key requirement; use the finished String instead.
Code Example
import java.util.List;
public class StringVsBuilder {
public static void main(String[] args) {
// USE STRING — single known concatenation, compiler handles it
String name = "Alice";
String greeting = "Hello, " + name + "!"; // compiler → StringBuilder internally
System.out.println(greeting); // Hello, Alice!
// USE STRING — return values, parameters, constants
String key = "user.name";
String value = System.getProperty(key);
// USE STRINGBUILDER — building in a loop
List<String> words = List.of("Java", " is", " great");
StringBuilder sb = new StringBuilder();
for (String w : words) {
sb.append(w); // same buffer, no new objects
}
String sentence = sb.toString(); // one String at the end
System.out.println(sentence); // Java is great
// USE STRINGBUILDER — conditional assembly
StringBuilder query = new StringBuilder("SELECT * FROM users");
boolean filterByAge = true;
boolean filterByCity = false;
if (filterByAge) query.append(" WHERE age > 18");
if (filterByCity) query.append(" AND city = 'Delhi'");
System.out.println(query.toString()); // SELECT * FROM users WHERE age > 18
}
}
Common Mistakes & Pitfalls
- Using
+to concatenate inside a loop — each iteration builds a newString(and a new builder under the hood), turning a simple join into O(n²). Declare oneStringBuilderbefore the loop andappend()inside it. - Wrapping a single concatenation in a
StringBuilder—new StringBuilder().append(a).append(b).toString()for a one-liner is pure verbosity; the compiler already handles the concatenation for plaina + b. - Using a
StringBuilderas aHashMapkey — it uses identity-based equality rather than text equality, so an equal-looking second builder will not find the entry. Keys must beString. - Returning a
StringBuilderfrom a method — hand back the finishedStringviatoString(). Leaking the mutable buffer lets a caller corrupt your data after the fact.
Check your understanding
Answer these without looking back at the article.
- Why is String concatenation with + in a loop slow in Java?
- What is the difference between StringBuilder and StringBuffer?
- How does the Java compiler optimise String + for single-line expressions?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.