How to use StringBuilder wisely?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
String concatenation in Java is easy to write, but repeated concatenation can quietly allocate many temporary objects. StringBuilder exists to make repeated edits cheap by storing characters in a mutable buffer. The class is simple, but using it well means understanding when it helps, when it does not, and how to avoid unnecessary work.
When StringBuilder Actually Helps
String is immutable, so an expression such as result = result + part produces a new string each time. In short code that does not matter much, and the Java compiler already optimizes some constant concatenation. The real benefit appears when you build a value inside a loop, while parsing input, or when many small fragments must be joined.
That example is readable, but it creates extra intermediate strings. A StringBuilder keeps a single growing buffer instead.
The improvement matters most when the loop is large or runs often.
Pick the Right String Tool
Not every concatenation needs StringBuilder. A plain String is fine for a few values in one expression.
For multi-step assembly in a single thread, use StringBuilder.
For synchronized access across threads, Java also provides StringBuffer, but most application code should not share a mutable text buffer between threads in the first place. If the data is already in a collection, String.join or Collectors.joining can be even cleaner than manual appends.
Use the simplest tool that matches the job. StringBuilder is a performance tool, not a default replacement for every string literal.
Pre-Size the Buffer for Large Builds
StringBuilder grows automatically, but growth means allocating a bigger internal array and copying characters. If you have a rough size estimate, pass an initial capacity.
This is not a magic optimization, but for large loops it removes some avoidable resizing. Estimate loosely; there is no need to calculate the exact character count.
Build in One Direction and Convert Once
A common mistake is calling toString() too early and then continuing to append elsewhere. Keep data in the builder until the final result is needed.
The fluent append style keeps code compact and avoids intermediate strings. It is also safer than mixing many + fragments over several lines where delimiters are easy to miss.
Reuse Carefully
Reusing a builder with setLength(0) can be useful inside hot loops, but only when the lifecycle is obvious. A reused builder that leaks between methods becomes harder to reason about than simply creating a new one.
If reuse makes control flow unclear, skip it. Readability usually wins unless profiling shows string building is a real bottleneck.
Common Pitfalls
- Replacing every
Stringexpression withStringBuildereven when a simple one-line concatenation is clearer. - Forgetting to pre-size the buffer in large loops where repeated growth becomes measurable.
- Calling
toString()repeatedly during construction instead of converting once at the end. - Sharing one mutable builder across threads instead of keeping it local to a method or task.
- Reusing a builder with
setLength(0)in ways that make stale content bugs harder to spot.
Summary
- Use
StringBuilderwhen text is assembled incrementally, especially inside loops. - Keep plain
Stringconcatenation for short, simple expressions. - Consider
String.joinor stream joining when the input is already a collection. - Set an initial capacity when the output is large enough that resizing is likely.
- Convert with
toString()once, near the point where the final string is needed.
Related reading
- How to use ThreeTenABP in Android Project
- How to use UTF-8 in resource properties with ResourceBundle
- How to use wait and notify in Java without IllegalMonitorStateException?
- How to use WeakReference in Java and Android development?
- How to use WebClient to execute synchronous request?
- How to verify that a specific method was not called using Mockito?
- How to view autoconfigure log output during spring boot tests integration tests
- How to view the list of compile errors in IntelliJ?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.