Text blocks
A text block is a string literal that spans several lines, written between triple quotes. You can paste JSON, SQL or HTML into the source as it is, and the compiler removes the indentation that only exists because of where the code sits. This page explains the compiler's three processing steps, shows each one with visible whitespace, and covers line endings, the related String methods and the traps people hit.
Contents
What a text block is and how the compiler processes it
Before Java 15, a multi-line string had to be built from pieces: "{\n" + " \"name\": \"Ana\"\n" + "}\n"\n"""""""
The compiler turns the text between the delimiters into an ordinary String
- Line terminators are normalized. Every
or\r\n in the source becomes\r , so the string does not depend on how the file was saved on Windows or Unix.\n - Incidental whitespace is removed. The compiler finds the smallest indentation among the non-blank lines and the line with the closing delimiter, removes that many characters from the start of every line, and removes all trailing whitespace from every line.
- Escape sequences are interpreted.
,\n ,\t and the two new escapes\" and\s are processed last, so an escaped space or newline is never stripped.\<line break>
All of this happens at compile time. The class file contains a normal string constant, so a text block costs nothing at run time and is interned like any other literal.
| Feature | Since | Best for |
|---|---|---|
| Text blocks, preview (JEP 355) | Java 13 | Historical |
\s\<line break> | Java 14 | Historical |
Text blocks standard (JEP 378), stripIndenttranslateEscapesformatted | Java 15 | JSON, SQL, HTML, test data in source |
String.indent(int)lines()strip() | Java 11 and 12 | Adjusting multi-line text at run time |
Every program here was run on JDK 21 to produce its output. They print each line between |
How indentation is removed
The same JSON is written three ways that differ only in where the closing delimiter sits, because its position is what controls how much indentation is kept.
public class Indentation {
// Shows each line between | markers, with spaces drawn as dots
static void show(String label, String s) {
System.out.println(label);
for (String line : s.split("\n", -1)) {
System.out.println(" |" + line.replace(' ', '.') + "|");
}
}
public static void main(String[] args) {
// Closing delimiter on its own line, aligned with the content
String a = """
{
"name": "Ana"
}
""";
show("a: closing quotes aligned with content", a);
// Closing delimiter moved 4 columns left: 4 spaces of indentation are kept
String b = """
{
"name": "Ana"
}
""";
show("b: closing quotes 4 columns further left", b);
// Closing delimiter right after the last line: no final newline
String c = """
one
two""";
show("c: closing quotes on the last content line", c);
String plain = "{\n \"name\": \"Ana\"\n}\n";
System.out.println("a equals the escaped literal: " + a.equals(plain));
System.out.println("a is the same object as it: " + (a == plain));
}
}
Output:
a: closing quotes aligned with content
|{|
|.."name":."Ana"|
|}|
||
b: closing quotes 4 columns further left
|....{|
|......"name":."Ana"|
|....}|
||
c: closing quotes on the last content line
|one|
|two|
a equals the escaped literal: true
a is the same object as it: true
- In
the closing quotes are in the same column asa , so all 16 columns of source indentation were removed. The relative two-space indent of{ survived. The closing quotes are on their own line, so the string ends with a newline, shown as the empty last line."name" - In
the closing quotes are 4 columns further left, so only 12 columns were removed and every line kept 4 leading spaces. Moving the closing delimiter left is the way to add indentation on purpose.b - In
the closing quotes followc directly, so there is no final newline, and the content lines alone decided the indentation.two equals the same text written with escapes, anda is true: both are compile-time constants with the same content, so they are the same interned object.a == plain
Trailing spaces, \s, line continuation and quotes
Step 2 also removes spaces at the end of each line, because editors add and remove them invisibly. The first block has a line ending in three spaces and a line ending in two spaces plus \sformatted
public class Escapes {
static void show(String label, String s) {
System.out.println(label);
for (String line : s.split("\n", -1)) {
System.out.println(" |" + line.replace(' ', '.') + "|");
}
}
public static void main(String[] args) {
// Line 1 ends in three spaces: removed.
// Line 2 ends in two spaces and \s: \s is one space and protects the spaces before it.
String trailing = """
three spaces stripped:
three spaces kept: \s
""";
show("trailing whitespace", trailing);
// A backslash at the end of a line joins it with the next line
String joined = """
This sentence is long, so it is split in the source \
but comes out as one line.
""";
show("line continuation", joined);
// Quotes need no escaping, except three in a row
String quotes = """
She said "hi". A text block starts with \""" and so on.
""";
show("quotes", quotes);
// formatted() fills placeholders, like String.format
String query = """
SELECT id, name
FROM users
WHERE age > %d AND city = '%s'
""".formatted(30, "Oslo");
show("formatted", query);
}
}
Output:
trailing whitespace
|three.spaces.stripped:|
|three.spaces.kept:...|
||
line continuation
|This.sentence.is.long,.so.it.is.split.in.the.source.but.comes.out.as.one.line.|
||
quotes
|She.said."hi"..A.text.block.starts.with.""".and.so.on.|
||
formatted
|SELECT.id,.name|
|FROM.users|
|WHERE.age.>.30.AND.city.=.'Oslo'|
||
- The three trailing spaces on the first line are gone. On the second line,
became a space in step 3, after stripping, and it also protected the two spaces before it, which were no longer trailing in step 2. The line ends in three dots.\s - javac's
warns "trailing white space will be removed" for that first line. The demo is compiled with-Xlint:text-blocks because the trailing spaces are the point of the example.-Xlint:-text-blocks - The backslash at the end of a line removed the line break, so two source lines became one output line. This keeps long lines readable in the source.
- Single and double quotes are written as they are. Only three quotes in a row must be escaped, as
.\""" filled the placeholders, likeformatted(30, "Oslo") . Use it only with trusted values in SQL; user input belongs inString.format parameters.PreparedStatement
Line endings
Because step 1 turns every line break into \n\r\r\n
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
public class LineEndings {
public static void main(String[] args) {
// Every line ends in \n, whatever line endings the source file uses
String plain = """
a
b
""";
System.out.println("plain: " + HexFormat.ofDelimiter(" ").formatHex(
plain.getBytes(StandardCharsets.US_ASCII)));
// HTTP needs CRLF: add \r yourself, the text block supplies the \n
String request = """
GET /index.html HTTP/1.1\r
Host: example.com\r
\r
""";
byte[] bytes = request.getBytes(StandardCharsets.US_ASCII);
System.out.println("request: " + bytes.length + " bytes, ends with "
+ HexFormat.ofDelimiter(" ").formatHex(bytes, bytes.length - 4, bytes.length));
System.out.println("CRLF count: " + request.split("\r\n", -1).length + " parts");
// Platform line separator, if a file must use the local convention
String local = plain.replace("\n", System.lineSeparator());
System.out.println("on this OS: " + HexFormat.ofDelimiter(" ").formatHex(
local.getBytes(StandardCharsets.US_ASCII)));
}
}
Output:
plain: 61 0a 62 0a
request: 47 bytes, ends with 0d 0a 0d 0a
CRLF count: 4 parts
on this OS: 61 0a 62 0a
- The plain block is
: "a", LF, "b", LF. It would be the same if the source file had been saved with Windows line endings.61 0a 62 0a - In the HTTP request, each
escape is followed by the block's own line break, giving\r . The request ends with\r\n , the empty line that ends HTTP headers, and splitting on CRLF gives 4 parts: two header lines, the empty line, and the empty rest.0d 0a 0d 0a isSystem.lineSeparator() on this Linux machine, so the last line is unchanged. On Windows it would print\n .61 0d 0a 62 0d 0a
Doing the same at run time: stripIndent, indent and translateEscapes
Text read from a file or a database gets no compiler processing. Java 15 exposed the compiler's algorithms as Stringindent
public class RuntimeIndent {
static void show(String label, String s) {
System.out.println(label);
for (String line : s.split("\n", -1)) {
System.out.println(" |" + line.replace(' ', '.').replace('\t', '>') + "|");
}
}
public static void main(String[] args) {
// Text read at run time (from a file, say) gets no automatic stripping
String fromFile = " <list>\n <item>one</item>\n </list>\n";
show("as read", fromFile);
// The empty last line (after the final \n) counts, like a closing """ at column 0
show("stripIndent() with a final newline", fromFile.stripIndent());
String noFinalNewline = fromFile.substring(0, fromFile.length() - 1);
show("stripIndent() without it", noFinalNewline.stripIndent());
// indent(n) adds n spaces to every line (or removes them if n is negative)
String item = "<item>two</item>\n<item>three</item>\n";
show("indent(2)", item.indent(2));
// A tab counts as ONE whitespace character, the same as a space
String mixed = "\t\tif (x) {\n y();\n\t\t}";
show("tabs and spaces mixed, then stripIndent()", mixed.stripIndent());
// translateEscapes turns the two characters \ and n into a real newline
String typed = "line1\\nline2\\tend";
System.out.println("before translateEscapes: " + typed);
show("after translateEscapes()", typed.translateEscapes());
}
}
Output:
as read
|........<list>|
|..........<item>one</item>|
|........</list>|
||
stripIndent() with a final newline
|........<list>|
|..........<item>one</item>|
|........</list>|
||
stripIndent() without it
|<list>|
|..<item>one</item>|
|</list>|
indent(2)
|..<item>two</item>|
|..<item>three</item>|
||
tabs and spaces mixed, then stripIndent()
|if.(x).{|
|......y();|
|}|
before translateEscapes: line1\nline2\tend
after translateEscapes()
|line1|
|line2>end|
- The trap:
on text ending instripIndent() removed nothing. Like a closing\n on its own line, the empty last line after the final newline counts towards the minimum indentation, and its indentation is 0. Without the final newline, 8 columns were removed.""" added two spaces to each line and normalized the line endings, adding a finalindent(2) . A negative argument removes up to that many leading whitespace characters.\n- Tabs are drawn as
. The two lines with two tabs and the line with eight spaces had a minimum indentation of 2 characters, so the tabs were removed but six of the eight spaces stayed. A tab counts as one character, not as a tab stop, which is why mixing tabs and spaces in a text block gives misaligned results.> turned the two-character sequences backslash-n and backslash-t, as a user might type them in a configuration file, into a real newline and tab.translateEscapes()
Traps: regex, percent signs and inserted values
Text blocks make some things easy that they do not actually do. Each part of the program shows one misunderstanding with input chosen to expose it.
import java.util.UnknownFormatConversionException;
import java.util.regex.Pattern;
public class TextBlockTraps {
public static void main(String[] args) {
// 1. A text block is not a raw string: backslashes in a regex still need doubling
String regex = """
\\d{4}-\\d{2}""";
Pattern date = Pattern.compile(regex);
System.out.println("regex " + regex + " matches 2026-11: "
+ date.matcher("2026-11").matches());
// 2. formatted() treats % specially: a LIKE pattern needs %%
String like = """
SELECT * FROM users WHERE name LIKE '%s%%'""".formatted("An");
System.out.println(like);
try {
String broken = """
SELECT * FROM t WHERE name LIKE '%an%' AND age > %d""".formatted(30);
System.out.println(broken);
} catch (UnknownFormatConversionException e) {
System.out.println("single % in formatted(): " + e.getClass().getSimpleName()
+ " " + e.getMessage());
}
// 3. Inserting a multi-line value: only its first line gets the template's indentation
String items = "<item>a</item>\n<item>b</item>";
String html = """
<list>
%s
</list>""".formatted(items);
System.out.println(html);
String fixed = """
<list>
%s</list>""".formatted(items.indent(2));
System.out.println(fixed);
// 4. An opening delimiter must be followed by a line break
System.out.println("one-line text block: not allowed, \"\"\"abc\"\"\" does not compile");
}
}
Output:
regex \d{4}-\d{2} matches 2026-11: true
SELECT * FROM users WHERE name LIKE 'An%'
single % in formatted(): UnknownFormatConversionException Conversion = '''
<list>
<item>a</item>
<item>b</item>
</list>
<list>
<item>a</item>
<item>b</item>
</list>
one-line text block: not allowed, """abc""" does not compile
- A text block is not a raw string. Escapes are still processed, so a regex digit class must be written
, exactly as in an ordinary literal. A single\\d is a compile error, "illegal escape character". The pattern then matched "2026-11".\d - In
,formatted starts a format specifier. The LIKE pattern% produced'%s%%' , but'An%' threw'%an%' :UnknownFormatConversionException is a valid hex float conversion, and%a after%' is not. Writean for a literal percent sign.%% - Inserting a multi-line value with
indents only its first line, because the template's indentation is part of the text before the placeholder. The fix puts%s at column 0 and indents the value itself with%s , which also supplies the line break beforeindent(2) .</list> - The opening
must be followed by a line break:""" on one line fails with "illegal text block open delimiter sequence, missing line terminator"."""abc"""
Choosing a string literal form
| Situation | Use |
|---|---|
| Short, single-line text | An ordinary "..." |
| Multi-line JSON, SQL, HTML, YAML or test data | A text block, closing delimiter aligned with the content |
| Long single line that should wrap in the source | Text block with \ |
| Trailing spaces that must survive | \s |
| CRLF line endings (HTTP, some file formats) | \r |
| Values inserted into a template | formatted(...)%% |
| Text read at run time | stripIndent()indent(n)translateEscapes() |
| User input inside SQL | Never formattedPreparedStatement |
A proposal for string interpolation built on top of text blocks, string templates, was previewed and then withdrawn; see