StringBuilder
StringBuilder is a mutable buffer of characters. You append pieces, then call toString() once. Use it when you would otherwise concatenate in a loop.
Detailed Explanation
String cannot grow. Each s = s + chunk allocates a new string and copies everything already in s. In a loop of n chunks that is about n² copied characters. StringBuilder keeps a resizable char (or byte) array, appends in amortized constant time, and builds the final String at the end.
The API is fluent: sb.append(name).append('=').append(value). append accepts primitives, objects (toString is called), and other builders. insert, delete, reverse, and setCharAt edit in place. length() is the number of characters currently stored. capacity() is the array size, which grows when needed, usually by doubling.
StringBuffer is the older, synchronized twin. It is safe for concurrent writes and slower when you do not need that. Almost all builders are local to one thread. Use StringBuilder. The compiler already rewrites a single expression like "a" + x + "b" into a builder. It does not rewrite a loop. That is the case you must write by hand.
You reach for a builder when the number of pieces is not known at compile time: joining query parts, formatting a table, reading chunks from a stream. You avoid it for one or two concatenations; + is clearer and the compiler already optimizes those. You avoid sharing a builder across threads unless you add your own locking, and even then a thread-local builder or a new one per call is simpler.
StringJoiner and String.join sit on top of a builder and handle separators so you do not write the "comma except the first" dance. Prefer them when you are joining a collection.
The cost of a builder is the extra object and the final copy into a String. Pre-size with new StringBuilder(expectedSize) when you know the order of magnitude; that avoids several array copies. Do not keep a long-lived builder as a field that grows forever; setLength(0) reuses the array, but a builder that once held a huge secret still holds a huge array until you replace it.
Code Examples
public class Csv {
static String csv(String[] cells) {
StringBuilder sb = new StringBuilder(cells.length * 8);
for (int i = 0; i < cells.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(cells[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(csv(new String[] {"a", "b", "c"})); // prints: a,b,c
}
}public class Join {
public static void main(String[] args) {
String line = String.join("-", "2026", "09", "12");
System.out.println(line); // prints: 2026-09-12
StringBuilder sb = new StringBuilder("code");
sb.reverse();
System.out.println(sb); // prints: edoc
}
}Common Gotchas
`StringBuilder` is not thread-safe
concurrent `append` calls can lose characters or throw. Use a local builder, or `StringBuffer` if you truly share it.
The compiler already builds a builder for `a + b + c`
hand-written builders pay off in loops and conditionals, not in one expression.
`append(char[])` shares no storage after `toString`
the resulting `String` is independent, but the builder still holds its array until you drop the reference.
Forgetting `toString()`
passing a builder where a `String` is required calls `toString` implicitly in concatenation, but an API that wants `String` will not compile.