Sub topic 11
Choosing the Right Java String Tool
Assume you know basic Java syntax, loops, methods, the String class, and the difference between objects and primitives. This chapter compares common ways to create and combine text: +, StringBuilder, String.join, text blocks, and formatted.
The best choice depends on the shape of the text, how often it changes, and whether several threads must use the same mutable object.
Use `+` for Small, Clear Concatenations
The + operator is usually the clearest choice when you combine a few values:
String name = "Ada";
int score = 42;
String message = "Player " + name + " scored " + score + " points.";
System.out.println(message);Java creates a new String for the result. A String is immutable, which means its characters cannot change after the object is created. An expression such as text + value therefore produces another string instead of modifying text.
This is appropriate for short expressions and occasional concatenation. The compiler can also optimize simple concatenations in one expression.
Repeated concatenation in a loop is different:
String result = "";
for (int i = 0; i < 1000; i++) {
result += i;
}Each += creates a new string containing the previous contents and the new value. As the result grows, the program repeatedly copies accumulated characters. For a large or unknown number of iterations, use StringBuilder.
Use `StringBuilder` for Repeated or Editable Text
StringBuilder is a mutable character buffer. Its append method adds text to the same builder, and toString() creates the final immutable String.
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 3; i++) {
builder.append("Item ").append(i).append('\n');
}
String result = builder.toString();
System.out.print(result);Use it when you build text in a loop, add pieces conditionally, or need to edit existing text:
StringBuilder builder = new StringBuilder("Hello, World");
builder.replace(0, 5, "Howdy");
builder.insert(5, "!");
builder.delete(6, 7);
builder.setCharAt(0, 'h');
System.out.println(builder); // howdy, WorldThe end index in replace and delete is exclusive. Check indexes carefully. An incorrect index causes StringIndexOutOfBoundsException, and an incorrect edit can produce valid but wrong text.
reverse() modifies the builder in place:
builder.reverse();This reverses UTF-16 code units. For ordinary English text that usually matches the visible characters, but some Unicode characters use surrogate pairs or combining marks. Do not assume that reversing arbitrary human-language text preserves user-perceived characters.
Use `String.join` for Delimited Values
String.join expresses a specific operation: placing a delimiter between values.
var tags = java.util.List.of("java", "strings", "performance");
String line = String.join(", ", tags);
System.out.println(line); // java, strings, performanceIt is clearer and safer than manually appending delimiters, especially when the number of values changes. It does not add a delimiter after the final value.
Use StringBuilder instead when each item needs custom formatting, conditions, or multiple lines.
Use Text Blocks for Fixed Multi-Line Content
A text block is a string literal written with three double quotes. It is useful for SQL, JSON, templates, and other content whose layout matters.
String json = """
{
"name": "Ada",
"active": true
}
""";
System.out.print(json);Java removes incidental indentation based on the closing delimiter. The result starts with { at the beginning of its line and ends with a newline because the closing delimiter is on its own line.
Place the closing delimiter differently when you need different trailing content:
String compact = """
first
second""";Here, the final newline before the closing delimiter is not part of the string.
A text block is still an ordinary String. It is best for mostly fixed content, not for repeated construction or many edits.
Combine Templates with `formatted`
Use formatted when a text block has placeholders:
String report = """
Name: %s
Score: %d
""".formatted("Ada", 42);
System.out.print(report);The format specifiers must match the supplied values. %s accepts a string representation, while %d expects an integer-compatible value. A mismatch can cause a formatting exception.
stripIndent() removes common indentation from an existing string. translateEscapes() interprets escape sequences such as \\n and \\t in an ordinary string:
String raw = "Name: %s\\nScore: %d";
String report = raw.translateEscapes().formatted("Ada", 42);
System.out.print(report);Use these methods deliberately. Calling translateEscapes() on user input can change its meaning, so treat external text as data rather than as an escape-encoded template.
Choose Based on the Job
| Task | Recommended tool | Main reason |
|---|---|---|
| Combine a few values once | `+` | Simple and readable |
| Build text repeatedly | `StringBuilder` | Avoids repeated copying |
| Join values with one delimiter | `String.join` | Handles separators clearly |
| Store fixed multi-line content | Text block | Preserves readable layout |
| Fill placeholders in a template | `formatted` | Separates layout from values |
| Share a mutable builder across threads | `StringBuffer` or other synchronization | `StringBuilder` is not thread-safe |
StringBuffer provides synchronized methods, but synchronization adds overhead and does not automatically make a larger sequence of operations logically safe. Prefer keeping a StringBuilder local to one thread. Use StringBuffer only when its synchronization matches a real requirement.
Exercise
Which tool should you choose to create one line containing 500 list values separated by commas, while applying custom formatting to each value?
Show answer
Use StringBuilder. It avoids repeated immutable-string copying and lets you format each value before appending its comma or other separator.