StringBuilder
StringBuilder is a mutable sequence of characters. Use it to build a String from many pieces β especially in loops β because repeated + on immutable String creates a new object every time and is quadratic in cost.
Usage
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("world!");
sb.append(" ").append(2026);
String result = sb.toString(); // "Hello, world! 2026"
Common methods
append(x)β append string, char, int, etc.insert(offset, x)β insert at positiondelete(start, end)β remove a rangereplace(start, end, str)β replace a rangereverse()β reverse in placetoString()β produce the final immutable Stringlength(),charAt(i),setLength(n)
StringBuilder vs StringBuffer
Both are mutable sequences. StringBuffer is thread-safe (synchronized); StringBuilder is not. Always use StringBuilder unless you genuinely share a single instance across threads without external synchronisation β you almost never do.
When to use StringBuilder
- Building strings in a loop: thousands of concatenations.
- Dynamic SQL or HTML assembly (prefer a templating tool when possible).
When you don't need it
// The compiler already converts simple concatenation to StringBuilder:
String s = "Hello, " + name + "!";
// Roughly equivalent to:
String s = new StringBuilder().append("Hello, ").append(name).append("!").toString();
So simple inline concatenation is fine. Only reach for explicit StringBuilder for loops or complex multi-step building.