Difficulty: Beginner
What are the differences between String, StringBuilder and StringBuffer, and when would you use each?
This is a classic warm-up, and the trap is that many candidates answer with a one-line table and stop. Let me give you the reasoning so you can answer the follow-ups too.
Start with String. It is immutable, so every modification produces a new object. That is perfect for constants, map keys and anything shared across threads, but it is expensive when you build text piece by piece. If you write s = s + i inside a loop of 10,000 iterations, each iteration allocates a new String and copies all previous characters. That is O(n squared) work overall and a lot of garbage.
StringBuilder fixes this. It is a mutable sequence of characters backed by an internal array that grows as needed. Calling append writes into the same buffer, only resizing occasionally (the capacity roughly doubles plus two each time). So building a string of n characters is O(n) overall. StringBuilder is not synchronized, so it is fast but not safe if several threads modify the same instance.
StringBuffer is the same API as StringBuilder but every public method is synchronized. It was in Java 1.0, while StringBuilder arrived in Java 5 as the unsynchronized twin. Because synchronization costs time and, more importantly, because you rarely share a string-building buffer between threads, StringBuffer is almost never the right choice today. Even when threads are involved, synchronizing individual methods does not make a sequence of operations atomic, so you would still need your own locking.
So the summary: String when the value does not change, StringBuilder for building text within one thread (the 95 percent case), StringBuffer only for legacy code or a genuinely shared buffer.
Here are the edge cases interviewers love. First, the compiler already optimizes simple concatenation. A statement like String s = "a" + b + "c" outside loops is compiled into StringBuilder calls (or invokedynamic with StringConcatFactory since Java 9), so do not obsess over it. The problem appears in loops, because a fresh builder is created per iteration.
Second, equals is not overridden in StringBuilder or StringBuffer. new StringBuilder("a").equals(new StringBuilder("a")) is false because it uses identity. To compare content, call toString first or use compareTo (available since Java 11).
Third, you can pre-size the builder with new StringBuilder(capacity) when you know roughly the final length, avoiding repeated array copying.
Fourth, StringBuilder has handy mutation methods that String lacks: reverse, insert, deleteCharAt, setCharAt and replace. The classic string reverse or palindrome question is easy with reverse.
Fifth, memory: builders are not pooled. There is no literal syntax for them, so they always live on the heap as ordinary objects.
Also mention that String.join and the streams Collectors.joining are convenient alternatives for joining collections, and they use StringBuilder internally. In a real project, I would reach for those before hand-rolling a loop.
public class BuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(0, "X");
System.out.println(sb);
StringBuilder p = new StringBuilder("a");
StringBuilder q = new StringBuilder("a");
System.out.println(p.equals(q));
System.out.println(p.toString().equals(q.toString()));
StringBuffer safe = new StringBuffer("sync");
safe.append(1).append(true);
System.out.println(safe);
String s = "";
for (int i = 0; i < 3; i++) {
s += i;
}
System.out.println(s);
}
}
reverse turns abcdef into fedcba, then insert puts X at index 0. equals on builders is identity based, so compare toString results for content.
String, StringBuilder, StringBuffer, Thread Safety, Performance