Sub topic 11
Choosing the Right Tool for the Job
This chapter pulls the earlier material together into decision rules. You will compare plain concatenation, StringBuilder, StringBuffer, String.join, String.format, formatted, and text blocks, and pick one for each task.
It assumes you have read the earlier chapters of this tutorial. You should know that String is immutable and why concatenating in a loop is costly. You should also know the main StringBuilder methods, how text blocks strip indentation, and how \ and \s work inside them. You need JDK 15 or later to run the examples.
The Candidate Tools
Each tool solves a different problem. The table summarizes what each is for and its main limit.
| Tool | Best for | Main limit |
|---|---|---|
| `+` operator | Joining a few known pieces once | Costly when repeated in a loop |
| `StringBuilder` | Building or editing text across many steps | Not thread-safe, more verbose than `+` |
| `StringBuffer` | Building text shared between threads | Locking overhead, rarely the right fix |
| `String.join` | Joining a collection or array with a delimiter | No per-element logic |
| `String.format` / `formatted` | Templates with padding, numbers, and dates | Format string errors appear at run time |
| Text block | Fixed multi-line literals such as JSON, SQL, or HTML | Content is fixed at compile time apart from placeholders |
No tool wins everywhere. The sections below give the reasons behind each row.
Plain Concatenation Is Fine More Often Than You Think
The + operator has a bad reputation, but most of it comes from one pattern: repeating += inside a loop. Outside loops, + is usually the best choice.
String name = "Ada";
int unread = 3;
String message = "Hello, " + name + "! You have " + unread + " unread messages.";
System.out.println(message);This is a single expression. The compiler turns it into one concatenation operation (since Java 9 through invokedynamic, before that through a hidden StringBuilder). It creates one result String and does not copy repeatedly.
Two cases are even cheaper:
- Constant expressions such as
"a" + "b"are folded at compile time. No concatenation happens at run time. finalvariables initialized with constants are also folded.
The cost appears when the concatenation is spread across loop iterations. Each s += x starts a new concatenation that copies everything accumulated so far. For n iterations, the total copying grows with the square of the final length. Rewriting the loop with StringBuilder makes the growth roughly linear.
When StringBuilder Is the Right Choice
Use StringBuilder when the text is assembled over several statements or iterations. It is also the right choice when you need to change text after you wrote it. Typical signs:
- A loop appends to a result.
- Pieces are added conditionally (
ifthis, then append that). - You need
insert,delete,replace,reverse,setCharAt, orsetLength. - You know roughly how large the result will be and want to presize it.
A frequent loop problem is the trailing delimiter. With a builder you can append the delimiter every time and trim it at the end with setLength.
import java.util.List;
public class JoinDemo {
public static void main(String[] args) {
List<String> tags = List.of("java", "strings", "builder");
StringBuilder sb = new StringBuilder();
for (String tag : tags) {
sb.append(tag).append(", ");
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 2);
}
System.out.println(sb); // java, strings, builder
System.out.println(String.join(", ", tags)); // java, strings, builder
}
}The if guard matters. Without it, an empty list would call setLength(-2) and throw StringIndexOutOfBoundsException.
Both lines print the same text, but the second is much shorter. This brings up the next tool.
Gotchas that apply to StringBuilder
- Do not concatenate inside
append.sb.append("x=" + x)creates a temporaryStringfirst, which defeats the point. Writesb.append("x=").append(x). - Watch
chararithmetic.sb.append('a' + 1)appends the number98, because'a' + 1is anint. Cast it with(char) ('a' + 1)to getb. - Builders do not override
equals. Two builders with the same text are notequals. Compare witha.toString().equals(b.toString()), or uses.contentEquals(sb)to compare aStringwith a builder. - Convert once. Call
toString()when you are done. Calling it inside a loop copies the buffer each time.
String.join and StringJoiner for Delimited Data
If the job is "put a delimiter between elements," use String.join. It accepts either varargs or any Iterable<? extends CharSequence>.
import java.util.List;
public class JoinDemo2 {
public static void main(String[] args) {
System.out.println(String.join("-", "2026", "11", "26")); // 2026-11-26
System.out.println(String.join(" | ", List.of("a", "b", "c"))); // a | b | c
}
}String.join removes the delimiter bookkeeping that causes bugs. It has two limits. The elements must already be CharSequence values, so numbers need converting first. It also cannot transform or skip elements. When you need that, use a stream with Collectors.joining(", "), or a StringBuilder loop if the logic is complex. StringJoiner adds a prefix and a suffix, such as [ and ], and is useful when you add elements one at a time.
StringBuilder or StringBuffer
The two classes have the same methods. The difference is that StringBuffer methods are synchronized, so concurrent calls on the same object do not corrupt it.
Choose by asking whether more than one thread will touch the same instance:
- Almost always no. A builder is typically a local variable inside a method. No other thread can see it. Use
StringBuilder. - Yes, and the threads call methods on the same object.
StringBufferguarantees that each single call is atomic. A sequence of calls is not atomic, though. Two threads doingappend(a).append(b)can still interleave their pieces. You often need external locking anyway.
For this reason, StringBuffer is mostly found in legacy code. In new code, prefer a local StringBuilder, or let each thread build its own result and combine the results afterward.
Text Blocks for Fixed Multi-Line Content
Use a text block when the text is mostly a literal that spans several lines. JSON, SQL, HTML, and expected test output are the usual cases. Compare the alternatives:
String json = "{\n" +
" \"name\": \"Ada\",\n" +
" \"age\": 36\n" +
"}\n";
String sameJson = """
{
"name": "Ada",
"age": 36
}
""";
System.out.println(json.equals(sameJson)); // trueBoth strings are equal, and the text block reads like the document itself. Remember the rules from the earlier chapters:
- The opening
"""must be followed by a line break. - The closing delimiter position, together with the least-indented content line, sets how much indentation is removed.
- Trailing spaces on each line are stripped. Use
\sto keep one. - A
\at the end of a line joins it to the next line. - Line breaks are normalized to
\n, whatever the line endings in your source file.
A text block is an ordinary String at run time, so you can call any String method on it.
Combining a Text Block with formatted
When a text block needs values, formatted fills in the placeholders. It is equivalent to String.format(block, args).
public class Report {
public static void main(String[] args) {
String[] names = {"Pen", "Notebook", "Stapler"};
int[] qty = {10, 2, 1};
String header = """
Order for %s
----------------
""".formatted("Acme");
StringBuilder body = new StringBuilder();
int total = 0;
for (int i = 0; i < names.length; i++) {
body.append(String.format("%-10s x%d%n", names[i], qty[i]));
total += qty[i];
}
String footer = "Total items: " + total;
System.out.println(header + body + footer);
}
}This program uses four tools, each for the job it suits:
- A text block with
formattedfor the fixed header. - A
StringBuilderfor the rows, whose count depends on the data. String.formatwith%-10sto pad each name to 10 characters.- Plain
+for the final one-time join of three parts.
It prints:
Order for Acme
----------------
Pen x10
Notebook x2
Stapler x1
Total items: 13Format Strings: When formatted Beats +
+ converts values with toString() and offers no control over layout. A format string gives you width, precision, and alignment:
double price = 4.5;
System.out.println("Price: " + price); // Price: 4.5
System.out.println("Price: %.2f".formatted(price)); // Price: 4.50The cost is that the format string is not checked by the compiler. A wrong specifier, such as %d for a double, throws IllegalFormatConversionException at run time. Locale also matters: %.2f uses the default locale and might print 4,50. When output must be stable, pass a locale explicitly with String.format(Locale.ROOT, "%.2f", price).
Formatting is also slower than + or append, since the format string is parsed on every call. This rarely matters, but avoid String.format in the innermost part of a hot loop.
Decision Process
The flowchart below turns the sections above into questions you can ask in order.
Common Mistakes in Tool Choice
- Using a builder for a one-line expression.
new StringBuilder().append(a).append(b).toString()is worse thana + b. It is longer and gains nothing. - Using
+=in a loop whose size depends on input. - Using
StringBuffer"to be safe." It adds locking cost and still does not make multi-call sequences atomic. - Using a text block for a single line. A normal string literal is clearer.
- Building a text block by concatenating lines in a loop. If the line count is dynamic, a
StringBuilder(orString.join("\n", lines)) is the right tool. A text block only suits text known at compile time. - Forgetting that the final newline is part of the text block. If the closing delimiter is on its own line, the string ends with
\n. Put the delimiter right after the last character to avoid it, or callstrip().
Exercise
A method receives a List<String> of words and must return them joined by single spaces, with every word converted to upper case. Which tool would you pick, and why? Write the code.
Show answer
The task has per-element logic (upper-casing) plus a delimiter. String.join alone cannot transform elements, so use a stream with Collectors.joining, or a StringBuilder loop. A stream version: words.stream().map(String::toUpperCase).collect(Collectors.joining(" ")). A builder version appends each upper-cased word and a space inside the loop, then trims the last space with setLength after checking that the length is greater than 0. Plain += in a loop would work for tiny input but costs quadratic copying as the input grows.
Exercise
You need a 6-line SQL query in source code, with one table name that varies and one user-supplied ID. How would you write it, and which part must not use formatted?
Show answer
Write the query as a text block. Use formatted only for the table name, and only if the name comes from a fixed list in your code, because table names cannot be bound as parameters. Pass the user-supplied ID as a ? placeholder bound through PreparedStatement.setLong or setString. Never insert the ID with formatted or +, because that opens the query to SQL injection.
Exercise
A teammate wraps a StringBuilder in a method and replaces it with StringBuffer "in case two threads call it." Each call creates its own builder as a local variable. Is the change useful?
Show answer
No. A local builder is not shared between threads, so synchronization has no benefit and only adds overhead. Each thread that calls the method gets its own builder. StringBuffer matters only when several threads call methods on the same instance, and even then a sequence of calls is not atomic without extra locking.