Module 10: Strings, Files, and Everyday Core APIs
StringBuilder for Efficient Text Building
Use StringBuilder when you need to build text step by step without creating wasteful temporary strings.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-17
Java version
Java 25 LTS
Learning goals
- Know when `StringBuilder` is the right tool
- Use `append()` clearly in loops
- Avoid overusing it in tiny one-off expressions
StringBuilder is mutable: It lets you grow text without creating a new string object on every append.
This matters most in loops and report generation: Repeated concatenation can create a lot of temporary objects, while StringBuilder stays focused on one evolving buffer.
Use it for structure, not cleverness: Readable append steps beat giant hard-to-read chains.
StringBuffer exists too: It is synchronized for thread-safe access, but StringBuilder is the usual default in normal single-threaded application code.
Runnable examples
Build a report line by line
StringBuilder builder = new StringBuilder();
builder.append("Report\n");
builder.append("- Users: 12\n");
builder.append("- Sales: 4\n");
System.out.println(builder);Expected output
Report - Users: 12 - Sales: 4
Mini exercise
Use `StringBuilder` to create a three-line invoice summary with labels and values.
Summary
- `StringBuilder` is for repeated mutable text assembly.
- It is especially useful inside loops.
- Prefer clarity over clever chained appends.
Next step
After building strings well, format them more cleanly with placeholders and templates.
Sources used