Text Blocks and String.format
Write multi-line strings with text blocks and format data with String.format patterns.
Text Blocks and String.format
Text blocks (Java 15+) allow multi-line string literals without escaping. Combined with String.format and formatted(), they make complex string output clean and readable.
What are Text Blocks?
A text block is a string literal enclosed in triple double quotes """. It preserves newlines and indentation automatically, eliminating escape sequences for multi-line content.
// Traditional multi-line string
String old = "SELECT id, name, email\n" +
"FROM users\n" +
"WHERE active = true\n" +
"ORDER BY name;";
// Text block (Java 15+) — much cleaner
String sql = """
SELECT id, name, email
FROM users
WHERE active = true
ORDER BY name;
""";
System.out.println(sql);