Builder: StringBuilder chains append calls in a loop

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.

Code
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
    sb.append(i).append(i < 5 ? "," : "");
}
System.out.println("Built string: " + sb);
Output
Built string: 1,2,3,4,5
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms