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 position
  • delete(start, end) β€” remove a range
  • replace(start, end, str) β€” replace a range
  • reverse() β€” reverse in place
  • toString() β€” produce the final immutable String
  • length(), 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.