Text Blocks
A text block is a multi-line string literal, written between triple double quotes ("""). It lets you write HTML, JSON, SQL, XML, email templates, and other multi-line text directly in Java source, laid out exactly as it should appear, without \n escapes, + operators, or escaped quotation marks. Text blocks became a standard feature in Java 15. The result is an ordinary String; only the way it is written in source code differs.
The Problem Text Blocks Solve
Before text blocks, multi-line text had to be built from many quoted pieces:
String json = "{\n" +
" \"id\": \"A-1042\",\n" +
" \"customer\": \"Ada\"\n" +
"}\n";
Every line needs quotes, an explicit \n, and a +, and every " inside the text must be escaped as \". The same value as a text block:
String json = """
{
"id": "A-1042",
"customer": "Ada"
}
""";
Syntax Rules
String s = """
first line
second line
""";
- The opening
"""must be followed by a line break. Content starts on the next line;"""Hello"""on one line is not allowed. - The closing
"""can be on its own line (the string then ends with a newline) or directly after the last character (no trailing newline). - Double quotes inside the text need no escaping. Only a sequence of three quotes (
""") must be escaped, as\""".
String a = """
Hello
""";
System.out.println(a.equals("Hello\n")); // true: closing delimiter on its own line
String b = """
Hello""";
System.out.println(b.equals("Hello")); // true: no trailing newline
How Indentation Is Handled
Text blocks are usually indented to match the surrounding code. The compiler removes that incidental indentation automatically, keeping only the essential indentation that belongs to the text.
The algorithm:
- Find the line with the smallest indentation, counting non-blank lines and also the line containing the closing
""". - Remove that many leading whitespace characters from every line.
- Strip trailing whitespace from every line.
String b = """
Indented
Base
""";
The least indented lines (Base and the closing delimiter) have four spaces, so four spaces are removed from every line:
Indented
Base
Using the closing delimiter to control indentation
Because the closing """ counts in step 1, moving it left adds indentation to the whole block:
String c = """
One
Two
""";
The closing delimiter is four spaces less indented than the content, so every line keeps four leading spaces:
One
Two
This is how you produce text that should be indented as a whole, such as a nested YAML section.
Mixing tabs and spaces for indentation produces confusing results, because each is counted as one whitespace character. Use one consistently, as most code formatters enforce.
Escape Sequences
All the usual escapes (\n, \t, \",