Text blocks

suggest change

A text block is a multi-line string literal. It starts with three double quotes and a line break, and ends with three double quotes:

String html = """
    <html>
        <body>
            <p>Hello, "world"</p>
        </body>
    </html>
    """;

Text blocks were a preview in Java 13 (JEP 355) and 14 (JEP 368) and became a standard feature in Java 15 (JEP 378). They need no flags on any current JDK.

Compare this with the same string written as a regular literal:

public class Basic {
    public static void main(String[] args) {
        String old = "<html>\n" +
                     "    <body>\n" +
                     "        <p>Hello, \"world\"</p>\n" +
                     "    </body>\n" +
                     "</html>\n";

        String html = """
            <html>
                <body>
                    <p>Hello, "world"</p>
                </body>
            </html>
            """;

        System.out.print(html);
        System.out.println(html.equals(old));
    }
}
<html>
    <body>
        <p>Hello, "world"</p>
    </body>
</html>
true

There are no \n escapes, no + and no escaped quotes. Note also that the result doesn't contain the 12 spaces that indent the text block in the source. Which whitespace is kept and which is removed is the main thing to understand about text blocks.

A text block is not a new type. The result is an ordinary String, and everything in Strings and String literals applies to it.

The opening delimiter

The opening """ must be followed by a line terminator (only whitespace may come between). The content starts on the next line. That means there are no one-line text blocks:

public class Bad {
    String s = """Hello""";
}
Bad.java:2: error: illegal text block open delimiter sequence, missing line terminator
    String s = """Hello""";
                  ^
Bad.java:2: error: illegal text block open delimiter sequence, missing line terminator
    String s = """Hello""";
                          ^
2 errors

For a single line, use a regular "..." literal.

Incidental and essential indentation

Text blocks are usually indented to match the surrounding code. That indentation is incidental: it's there because of where the code is, not because you want it in the string. Indentation relative to other lines is essential and is kept.

The compiler removes incidental indentation like this:

  1. It looks at every non-blank line of the content and at the line with the closing """.
  2. It finds the smallest number of leading whitespace characters among them.
  3. It removes that many characters from the start of every non-blank line.

The closing delimiter matters, so its position is how you control indentation. The example below shows spaces as dots, and [ and ] mark the start and end of the string:

public class Indent {
    static void show(String label, String s) {
        // show spaces as dots and mark start and end of the string
        System.out.println(label + ":");
        System.out.println("[" + s.replace(' ', '.') + "]");
    }

    public static void main(String[] args) {
        // closing delimiter on its own line, aligned with content
        String a = """
            SELECT id, name
              FROM users
            """;
        show("aligned", a);

        // closing delimiter moved left: 4 spaces of indentation are kept
        String b = """
                SELECT id, name
                  FROM users
            """;
        show("delimiter to the left", b);

        // closing delimiter moved right: it doesn't count
        String c = """
            SELECT id, name
              FROM users
                    """;
        show("delimiter to the right", c);

        // closing delimiter at the end of the last line: no trailing newline
        String d = """
            SELECT id, name
              FROM users""";
        show("no final newline", d);
    }
}
aligned:
[SELECT.id,.name
..FROM.users
]
delimiter to the left:
[....SELECT.id,.name
......FROM.users
]
delimiter to the right:
[SELECT.id,.name
..FROM.users
]
no final newline:
[SELECT.id,.name
..FROM.users]

What to take from it:

The FROM line keeps its 2 extra spaces in every case: that's essential indentation.

Blank lines

Lines that are empty or contain only whitespace are ignored when computing indentation, and they end up empty in the result. You can't accidentally break the indentation with a blank line that has fewer (or no) spaces.

Tabs and spaces

The compiler counts whitespace characters, it doesn't expand tabs. A tab counts as one character, same as a space. If some lines are indented with tabs and others with spaces, the result is probably not what you want. Here the first line is indented with two tabs and the second with 8 spaces:

String s = """
		first
        second
        """;
first
......second

The minimum indentation is 2 (the two tabs), so the line with spaces loses only 2 of its 8 spaces. Compile with -Xlint:text-blocks (or -Xlint:all) and javac warns about it:

$ javac -Xlint:text-blocks Tabs.java
Tabs.java:3: warning: [text-blocks] inconsistent white space indentation
        String s = """
                   ^

The fix is to use one kind of whitespace for indentation, which most editors and formatters do for you.

Trailing whitespace is removed

After removing incidental indentation, the compiler also strips trailing whitespace from every line. This is deliberate: trailing spaces are invisible in editors and often removed by them, so the meaning of the code shouldn't depend on them.

When you need trailing spaces (fixed-width output, Markdown line breaks), use the \s escape. It means a single space, and since escapes are translated after stripping, it also protects the spaces before it.

In the source below, red is followed by three spaces:

String colors = """
    red   
    green \s
    blue\s\s\s
    """;
System.out.print(colors.replace(' ', '.'));
red
green..
blue...

The spaces after red are gone. green \s keeps the real space plus the escaped one. With -Xlint:text-blocks javac warns about the stripped spaces:

Escapes.java:5: warning: [text-blocks] trailing white space will be removed
        String colors = """
                        ^

Escape sequences

All escapes of regular string literals work in text blocks: \n, \t, \", \\ and so on. Two escapes were added in Java 15 for text blocks:

String sentence = """
    Text blocks keep the source readable \
    even when the resulting string \
    is a single long line.""";
System.out.println(sentence);
Text blocks keep the source readable even when the resulting string is a single long line.

Note the space before each \. Trailing whitespace is stripped before the escape is processed, but a space followed by \ is not trailing, so it's kept.

Quotes

One or two double quotes in a row need no escaping. Only a sequence of three would end the text block, so escape the first one:

String quotes = """
    She said "hi" and ""
    A text block ends with \""" and starts with \"""
    """;
System.out.print(quotes);
She said "hi" and ""
A text block ends with """ and starts with """

Backslashes still need escaping

A text block is not a raw string. A backslash still starts an escape sequence, so regular expressions and Windows paths need \\, and JSON escapes like \n inside a JSON string must be written as \\n. Java has no raw string literals.

Line endings

Whatever line terminators your source file uses (\n on Unix, \r\n on Windows, or a mix), every line in a text block ends with \n. The same source compiles to the same string on every platform:

// this file is saved with Windows CRLF line endings
String s = """
    one
    two
    """;
System.out.println(s.contains("\r"));
System.out.println(s.length());
false
8

If a protocol needs \r\n (HTTP, SMTP, CSV files for some spreadsheets), either add \r at the end of each line, where the real line break supplies the \n:

String crlf = """
    HTTP/1.1 200 OK\r
    Content-Length: 0\r
    \r
    """;
System.out.println(crlf.replace("\r", "\\r").replace("\n", "\\n\n"));
HTTP/1.1 200 OK\r\n
Content-Length: 0\r\n
\r\n

or convert afterwards with s.replace("\n", "\r\n"). For the line separator of the current OS, use System.lineSeparator() (see Platform independent new line separator).

The order in which the compiler processes a text block is:

  1. Normalize line terminators to \n.
  2. Remove incidental indentation and trailing whitespace.
  3. Translate escape sequences.

Because escapes come last, a \n or \r written as an escape is never touched by steps 1 and 2.

Helper methods on String

Java 15 added three String methods that go with text blocks.

stripIndent() runs the indentation and trailing whitespace algorithm on any string at runtime. Useful for text read from a file or built dynamically.

translateEscapes() interprets escape sequences in a string at runtime, as if it were a literal. Useful for config values that contain \t or \n as two characters.

formatted(args...) is String.format as an instance method, which reads well after a text block.

public class Methods {
    public static void main(String[] args) {
        // stripIndent: the same algorithm the compiler uses, at runtime
        String raw = "      <ul>\n        <li>one</li>\n      </ul>";
        System.out.println(raw.stripIndent());
        // the empty last line after a final \n has zero indentation,
        // just like a closing delimiter in column 0: nothing is stripped
        System.out.print((raw + "\n").stripIndent());

        // translateEscapes: interpret \n, \t, \s, \" ... in a runtime string
        String fromConfig = "Name:\\tAlice\\nCity:\\tParis\\n";
        System.out.println(fromConfig);
        System.out.print(fromConfig.translateEscapes());

        // formatted: a text block as a format string
        String json = """
            {
              "id": %d,
              "name": "%s",
              "active": %b
            }
            """.formatted(42, "Alice", true);
        System.out.print(json);

        // indent: add (or remove) indentation to every line
        String body = """
            return a + b;
            """;
        System.out.print("int add(int a, int b) {\n" + body.indent(4) + "}\n");
    }
}
<ul>
  <li>one</li>
</ul>
      <ul>
        <li>one</li>
      </ul>
Name:\tAlice\nCity:\tParis\n
Name:	Alice
City:	Paris
{
  "id": 42,
  "name": "Alice",
  "active": true
}
int add(int a, int b) {
    return a + b;
}

The second stripIndent call shows a subtle point: stripIndent treats the last line specially, the same way the compiler treats the closing delimiter line. When the string ends with \n, the last line is empty and has zero indentation, so nothing is removed.

indent(n) (Java 12) is not specific to text blocks, but it's handy for nesting one block inside another. It also normalizes line endings and makes sure the result ends with \n.

For more on format specifiers see String formatting.

Text blocks are constants

A text block is a constant expression, just like "...". The processing happens at compile time, so there's no runtime cost, and equal text blocks and string literals are the same interned String object. You can also use a text block as a case label or in an annotation:

public class Constant {
    static final String GREETING = """
        hello
        """;

    static String kind(String s) {
        return switch (s) {
            case """
                hello
                """ -> "greeting";
            default -> "other";
        };
    }

    public static void main(String[] args) {
        String literal = "hello\n";
        System.out.println(GREETING == literal);     // same interned constant
        System.out.println(kind(literal));
        System.out.println(GREETING.length());
        System.out.println(GREETING.getClass().getName());
    }
}
true
greeting
6
java.lang.String

Don't rely on == for strings in real code; see Pitfall: using == to compare strings.

Practical uses: SQL, regex, JSON, HTML

Text blocks pay off for any embedded "other language" whose layout helps readability.

import java.util.regex.Pattern;

public class Uses {
    // SQL: keep it a constant, pass values as ? parameters
    static final String FIND_ORDERS = """
        SELECT o.id, o.total, c.name
          FROM orders o
          JOIN customers c ON c.id = o.customer_id
         WHERE o.status = ?
           AND o.created_at >= ?
         ORDER BY o.created_at DESC
        """;

    // regex: COMMENTS mode ignores whitespace and # comments
    static final Pattern DATE = Pattern.compile("""
        (?<year>\\d{4})   # year
        -
        (?<month>\\d{2})  # month
        -
        (?<day>\\d{2})    # day
        """, Pattern.COMMENTS);

    record Item(String name, int qty) {}

    static String toHtml(String title, Item... items) {
        StringBuilder rows = new StringBuilder();
        for (Item it : items) {
            rows.append("""
                <tr><td>%s</td><td>%d</td></tr>
                """.formatted(it.name(), it.qty()));
        }
        return """
            <table>
              <caption>%s</caption>
            %s</table>
            """.formatted(title, rows.toString().indent(2));
    }

    public static void main(String[] args) {
        System.out.print(FIND_ORDERS);

        var m = DATE.matcher("released 2020-09-15");
        if (m.find()) {
            System.out.println(m.group("year") + "/" + m.group("month") + "/" + m.group("day"));
        }

        System.out.print(toHtml("Stock", new Item("apple", 3), new Item("pear", 7)));
    }
}
SELECT o.id, o.total, c.name
  FROM orders o
  JOIN customers c ON c.id = o.customer_id
 WHERE o.status = ?
   AND o.created_at >= ?
 ORDER BY o.created_at DESC
2020/09/15
<table>
  <caption>Stock</caption>
  <tr><td>apple</td><td>3</td></tr>
  <tr><td>pear</td><td>7</td></tr>
</table>

Some advice:

No string interpolation

Text blocks don't support embedded expressions like ${name}. Java 21 and 22 had string templates (STR."Hello \{name}", JEPs 430 and 459) as a preview, but they were withdrawn and removed in Java 23, and no replacement has shipped as of Java 25. Use formatted, String.format, MessageFormat, concatenation or a template library.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents