StringBuilder & String Formatting
StringBuilder & String Formatting
In the previous lesson you explored the String class and its many useful methods. You may have noticed one quirk: every time you modify a String, Java silently creates a brand-new object in memory. For occasional edits that is fine, but inside a loop — or when building a long text piece by piece — it becomes expensive. This is where StringBuilder steps in. You will also learn String.format and printf, two tools that let you produce polished, structured output without messy concatenation.
Why Strings Are Immutable
String objects in Java are immutable — once created, the characters inside cannot change. When you write:
Java creates six String objects here — one empty, then one for each concatenation. With five iterations that is almost unnoticeable, but with thousands of iterations it wastes significant memory and time.
StringBuilder: A Mutable Character Buffer
StringBuilder keeps a single resizable character buffer. You modify it in place — no new objects are created for each change. The basic pattern is: create, mutate repeatedly, then call toString() once at the end.
One StringBuilder object instead of six String objects — same output, much less waste.
Key StringBuilder Methods
All mutation methods return this, so you can chain them:
append(value)— adds any value (String, int, double, char, boolean, …) to the end.insert(index, value)— inserts at a specific position.replace(start, end, str)— replaces characters fromstart(inclusive) toend(exclusive).delete(start, end)— removes the characters in that range.reverse()— reverses the entire buffer.length()— current number of characters.toString()— converts the buffer to an ordinary immutableString.
StringBuilder, you can write: new StringBuilder().append("A").append("B").append("C").toString() all on one line.
Building a CSV Row — a Practical Example
This pattern — accumulate with a StringBuilder, add separators conditionally, call toString() — appears everywhere in real Java code.
String.format — Clean Templated Strings
String.format works like a template engine. You write a format string with placeholders (format specifiers), and the method fills them in:
The most common specifiers:
%s— any object, converted viatoString().%d— integer (int,long).%f— floating-point;%.2fmeans two decimal places.%n— platform-correct newline (prefer this over\nin format strings).%%— a literal percent sign.
%10s right-pads a string in a field of 10 characters; %-10s left-aligns it. Useful for printing tables.
printf — Format and Print in One Step
System.out.printf applies the same format string but prints directly — no intermediate String variable needed:
Output:
%n (or \n) when you want each call on its own line, unlike println which adds one for you.
Choosing the Right Tool
- Simple, one-time concatenation — the
+operator is fine; the compiler optimises it. - Building text across many steps or in a loop — use
StringBuilder. - Producing formatted output (tables, reports, labels) — use
String.formatorprintf.
StringBuffer in older code. It is thread-safe but slower. Unless you are sharing a buffer between threads, always prefer StringBuilder.
Summary
String immutability is a feature, not a bug — but it means heavy concatenation in loops wastes memory. StringBuilder gives you a single mutable buffer you can append, insert, delete, and reverse before converting to a String once with toString(). String.format and printf let you embed values into readable templates using format specifiers such as %s, %d, and %.2f, making structured output clean and maintainable. With these tools you can handle nearly every text-building task in Java efficiently.