Core Java · 319 words · 2 minute read
Java StringBuilder: Build Text Efficiently Without Losing Clarity
By Priyanshu Rauth · Published 2026-09-04 · Updated 2026-09-04
Java String values are immutable: a method such as replace returns a new value instead of changing the original. That property makes Strings easy to share, but it also means repeated + concatenation in a loop can allocate many intermediate objects. StringBuilder is the standard mutable buffer for one-threaded text construction.
Use a builder for accumulated output
A builder is most helpful when the final length grows as a loop runs: formatting a table, compressing repeated characters, or constructing a result from many tokens. It is not a requirement for a simple expression such as "Hello, " + name. Choose it when it makes both the allocation pattern and the code clearer.
public class Main {
static String labels(int count) {
StringBuilder result = new StringBuilder();
for (int value = 1; value <= count; value++) {
if (value > 1) result.append(", ");
result.append("item-").append(value);
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(labels(3));
}
}The output is item-1, item-2, item-3. Separating delimiter placement from item placement avoids an unwanted trailing comma.
Mutation is deliberate
append, insert, delete, setCharAt, and reverse change the builder. Convert it to a String when the result crosses an API boundary or should no longer change. Do not keep a builder in a shared object merely to avoid allocation; that makes unrelated calls influence each other. For concurrent writes, use a local builder or consider synchronization only when the design genuinely requires sharing.
Common mistakes
- Calling
toString()repeatedly inside the build loop. - Using
deleteCharAt(length()); the final valid index islength() - 1. - Assuming String methods mutate their receiver.
- Reversing UTF-16 code units when a requirement is about Unicode code points.
Practice next
Try reverse string first, then string compression and remove adjacent duplicates. Each demonstrates a different builder role: ordered append, run flushing, and stack-like mutation. The Strings compiler page is a good place to change one input at a time and inspect why the output changes.
Continue with the Java practice path · Try code in the Java compiler