Lesson · Strings & Text
StringBuilder and StringBuffer: text that changes
10 min readMutable Text
When strings are built in loops or edited in place, the mutable buffers earn their keep. One is fast and single-threaded; the other synchronises and rarely wins.
Why a mutable buffer exists
Every String operation returns a new object. Concatenating inside a loop therefore allocates a new string per round and copies the accumulated text each time: quadratic work hidden in linear-looking code. A StringBuilder is a growable char store with append methods that mutate it in place, turning the same loop into linear work.
The compiler already rewrites single expressions ("a" + b + "c" becomes one builder sequence), so the classic advice has an inverse form that people forget: StringBuilder is NOT needed for one-shot concatenation, and reaching for it there is noise. The tool is for accumulation across iterations, or when edits are interleaved with logic.
The operations worth knowing
append covers every type, insert(index, ...) splices mid-string, deleteCharAt and delete(begin, end) remove ranges, replace(begin, end, text) substitutes, reverse flips the whole buffer, and setLength(0) empties it for reuse. All mutate and return the same builder, so calls chain.
toString() materialises a String snapshot: later edits to the builder do not appear in it. And reuse across loop iterations is a legitimate pattern (clear with setLength(0) rather than allocating a new builder), though modern JVMs make fresh builders cheap, and micro-optimising into unclear reuse is usually the wrong trade.
StringBuffer: the synchronised sibling
StringBuffer is the 1995-era class: same API, every method synchronised. StringBuilder arrived in Java 5 as the unsynchronised replacement, and the guidance stands: buffers of text almost never cross threads, so the synchronisation is cost without benefit. Choose StringBuilder everywhere; StringBuffer appears in old code, in APIs requiring it, and in interviews asking this exact difference.
The same reasoning as HashMap versus Hashtable, and ArrayList versus Vector: the early collections synchronised by default, single-threaded use dominated, and the modern classes dropped the lock. If a builder genuinely crosses threads, the sane design shares the finished String, not the mutable buffer.
Building text in practice
The idiomatic build: new builder, append in a loop with delimiters handled inside the loop (first-flag or prefix-on-index-greater-than-zero), toString at the end. Joining a collection is nicer with String.join when the text is uniform; the builder is for when the pieces need logic between them.
Chain comparisons (compareTo == 0 checks) and small formatting tasks compose well here. And a closing habit from the API topic: prefer append(char) over append(String) of a one-character string, and reuse append chains over repeated toString calls in the loop, because each toString outside the loop is a full copy.
If the loop concatenates, the builder is mandatory
String s = ""; for (...) { s += item; } allocates a new string per iteration and copies the accumulation each time: O(n squared) for n appends. The same loop with a StringBuilder appends in place: O(n). This is the most common performance bug in beginner Java code, and the compiler cannot fix it because the result feeds the next iteration.
Interview angles
StringBuilder versus StringBuffer?+
Same API. StringBuffer synchronises every method (legacy, Java 1.0); StringBuilder does not (Java 5). Single-threaded text building is the norm, so StringBuilder is the default and the synchronised version only appears in legacy code.
When does string concatenation become quadratic?+
When the accumulated value is fed back into the next concatenation: s = s + piece inside a loop. Each round copies everything so far. One-shot expressions are fine; the compiler folds them into a single builder.
How do you insert in the middle of a string efficiently?+
Do not, on a String: substring joins copy. With StringBuilder, insert(index, ...) shifts the tail in its internal array, linear in the length but allocation-free per operation. Build first, then materialise one String.