StringBuilder & Text Blocks in Java

From the Java cheat sheet · Strings & Text Blocks · verified Jul 2026

StringBuilder & Text Blocks

Efficient concatenation, multi-line text, and formatting.

java
// Quick Reference
var sb = new StringBuilder();
sb.append("a").append("b");
String out = sb.toString();

String json = """
    { "name": "Sam" }
    """;                 // text block
💡 Build strings in loops with StringBuilder - "+" in a loop creates many objects.
⚡ Text blocks strip incidental indentation based on the closing """ position.
📌 "template".formatted(args) is a concise instance-method alternative to String.format.
🟢 %s (string), %d (integer), %f (float), %n (newline) are the common format specifiers.
stringbuildertext-blocks

More Java tasks

Back to the full Java cheat sheet