All topics
library
beginner

Text Blocks & String Templates

Write multi-line strings cleanly with text blocks and understand the coming String templates feature.

Text blocks (Java 15) provide multi-line string literals without escape sequences for newlines and quotes.

Text blocks = WYSIWYG for strings. Instead of assembling a letter from fragments with explicit 'new line' instructions, you type the letter as it should appear. The formatter (compiler) handles the rest.

Key Concepts

1
Syntax: triple quotes with opening on its own line: String json = """ { "name": "Alice", "age": 30 } """;
2
Features: - Automatic indentation stripping: the closing """ position determines the base indentation - No need to escape double quotes (single quotes work too) - \n, \t, and other escapes still work - Trailing whitespace is stripped (use \s to preserve) - Line continuation: \ at end of line prevents the newline
3
Incidental vs essential whitespace: the compiler strips common leading whitespace (incidental). The remaining whitespace is essential (part of the string).
4
Formatting: combine with String.formatted() for parameterized text blocks: String sql = """ SELECT * FROM %s WHERE id = %d """.formatted(table, id);
5
String templates (preview in Java 21-22): STR."Hello \{name}" for interpolation without format strings. Still in preview — not finalized. Use .formatted() for now.