Master Java Text Blocks: Simplify Multiline Strings in JDK 13‑15
This article explains Java's Text Block feature (JEP 355), showing how it turns cumbersome, escape‑heavy multiline strings into clean, readable literals, details its processing steps, new escape sequences, and how to control indentation with the indent() method.
What are Text Blocks?
Text Blocks are a JDK language enhancement (JEP 355) that were previewed in JDK 13 and JDK 14 and became a permanent feature in JDK 15. A Text Block is a multiline string literal that does not require most escape characters.
Motivation
Embedding formats such as XML, JSON, or SQL in ordinary Java string literals requires extensive escaping of quotes and newline characters, which makes the source hard to read. For example, a two‑key JSON snippet written with classic string concatenation looks like:
String json = "{
" +
"\"name\": \"FunTester\",
" +
"\"age\": 30
" +
"}";Text Block Syntax
Using a Text Block the same JSON can be expressed concisely with triple quotes:
String json = """
{
"name": "FunTester",
"age": 30
}
""";The opening triple quotes start a Text Block; the content begins on the next line, and any characters after the opening delimiter on that line must be blank.
Processing Rules
All line terminators are normalized to LF, eliminating Windows/Unix differences.
Common leading whitespace is stripped. The smallest indentation shared by all lines is removed from each line.
Escape sequences are interpreted. Text Blocks support the same escapes as regular strings ( \t, \n, etc.) and introduce two new ones: \s – inserts an explicit space. \<eol> – line‑continuation indicator that allows a logical line to be split across physical lines without inserting a real line break.
Controlling Indentation
If additional leading spaces are required, the indent(int) method can be applied to the Text Block result:
String json = """
{
"name": "FunTester",
"age": 30
}
""".indent(4);The call adds four spaces to the beginning of each line, producing the following console output:
{
"name": "FunTester",
"age": 30
}Line Continuation with \<eol>
The new line‑continuation escape lets a single logical line be split across multiple physical lines without creating actual line terminators. Example:
String text = """
1
2 \<eol>
3 \<eol>
4
5
""";Printing text yields:
1
2 3 4
5Escaping Triple Quotes
To embed triple quotes inside a Text Block, escape only the first quote:
String quote = """
Test text \""";The resulting output is:
Test text """Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
