Repeated append() calls mutate the same buffer instead of allocating a new String on every step, which is what makes StringBuilder far cheaper than += concatenation inside a loop. Each call also returns the builder itself, so the calls can be chained.
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(i < 5 ? "," : "");
}
System.out.println("Built string: " + sb);
Built string: 1,2,3,4,5
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27