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". Every quote was escaped and every line break written as \n, so pasted JSON, SQL or HTML became hard to read and easy to break. A text block is a literal that starts with """ and a line break and ends at the next """. Inside it, line breaks are real and " needs no escape.

The compiler turns the text between the delimiters into an ordinary String constant in three steps, always in this order:

  1. Line terminators are normalized. Every \r\n or \r in the source becomes \n, so the string does not depend on how the file was saved on Windows or Unix.
  2. 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.
  3. Escape sequences are interpreted. \n, \t, \" and the two new escapes \s and \<line break> are processed last, so an escaped space or newline is never stripped.

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.

Text blocks and related features, by version
FeatureSinceBest for
Text blocks, preview (JEP 355)Java 13Historical
\s and \<line break> escapes, second preview (JEP 368)Java 14Historical
Text blocks standard (JEP 378), stripIndent, translateEscapes, formattedJava 15JSON, SQL, HTML, test data in source
String.indent(int), lines(), strip()Java 11 and 12Adjusting multi-line text at run time

Every program here was run on JDK 21 to produce its output. They print each line between | markers with spaces drawn as dots, so the whitespace is visible.

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.

Java
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:

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 a the closing quotes are in the same column as {, so all 16 columns of source indentation were removed. The relative two-space indent of "name" survived. The closing quotes are on their own line, so the string ends with a newline, shown as the empty last line.
  • In b 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.
  • In c the closing quotes follow two directly, so there is no final newline, and the content lines alone decided the indentation.
  • a equals the same text written with escapes, and a == plain is true: both are compile-time constants with the same content, so they are the same interned object.

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 \s. The others show the line-continuation escape, quotes, and formatted.

Java
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:

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, \s 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.
  • javac's -Xlint:text-blocks 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.
  • 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 \""".
  • formatted(30, "Oslo") filled the placeholders, like String.format. Use it only with trusted values in SQL; user input belongs in PreparedStatement parameters.

Line endings

Because step 1 turns every line break into \n, a text block never contains \r unless you write it. That is right for most uses, but some protocols require CRLF. The program prints the bytes of a plain block, an HTTP request that needs \r\n, and the plain block converted to the platform's separator.

Java
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:

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 61 0a 62 0a: "a", LF, "b", LF. It would be the same if the source file had been saved with Windows line endings.
  • In the HTTP request, each \r escape is followed by the block's own line break, giving \r\n. The request ends with 0d 0a 0d 0a, the empty line that ends HTTP headers, and splitting on CRLF gives 4 parts: two header lines, the empty line, and the empty rest.
  • System.lineSeparator() is \n on this Linux machine, so the last line is unchanged. On Windows it would print 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 String methods, and Java 12 had already added indent. The sample text is an indented XML fragment, first with and then without its final newline, because that one character changes the result.

Java
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:

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: stripIndent() on text ending in \n removed nothing. Like a closing """ 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.
  • indent(2) added two spaces to each line and normalized the line endings, adding a final \n. A negative argument removes up to that many leading whitespace characters.
  • 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.
  • translateEscapes() 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.

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.

Java
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:

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 \\d, exactly as in an ordinary literal. A single \d is a compile error, "illegal escape character". The pattern then matched "2026-11".
  • In formatted, % starts a format specifier. The LIKE pattern '%s%%' produced 'An%', but '%an%' threw UnknownFormatConversionException: %a is a valid hex float conversion, and %' after an is not. Write %% for a literal percent sign.
  • Inserting a multi-line value with %s 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 indent(2), which also supplies the line break before </list>.
  • The opening """ must be followed by a line break: """abc""" on one line fails with "illegal text block open delimiter sequence, missing line terminator".

Choosing a string literal form

Which form to use
SituationUse
Short, single-line textAn ordinary "..." literal
Multi-line JSON, SQL, HTML, YAML or test dataA text block, closing delimiter aligned with the content
Long single line that should wrap in the sourceText block with \ at the ends of lines
Trailing spaces that must survive\s at the end of the line
CRLF line endings (HTTP, some file formats)\r at the end of each line
Values inserted into a templateformatted(...), with %% for literal percent signs
Text read at run timestripIndent(), indent(n), translateEscapes()
User input inside SQLNever formatted; use PreparedStatement parameters

A proposal for string interpolation built on top of text blocks, string templates, was previewed and then withdrawn; see string templates for what happened and what to use today. For formatting options, see string formatting.