String ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-12-02

Text Blocks in Java

Try putting a small JSON document into a regular Java string:

String json = "{\n" +
              "  \"name\": \"Anna\",\n" +
              "  \"age\": 30\n" +
              "}\n";

Four lines of data turned into a pile of \n, \" and plus signs. It is easy to get wrong and hard to read what JSON comes out without running the code. With a text block the same literal looks exactly like the JSON itself:

String json2 = """
        {
          "name": "Anna",
          "age": 30
        }
        """;

System.out.println(json.equals(json2)); // true — the strings match character for character

A text block is a multi-line Java string literal enclosed in triple quotes """. Inside it you can write line breaks and quotes without escaping them, and the compiler removes the extra indentation that comes from code formatting. The result is an ordinary String: there is no new type, and every string method works as before. Text blocks appeared as a preview feature in Java 13 (JEP 355), got the \s and \<line-terminator> escapes in the second preview in Java 14, and became a permanent part of the language in Java 15 (JEP 378).

Why text blocks exist

Text blocks let you paste ready-made multi-line text into Java code — JSON, SQL, HTML, XML, an email template, the expected output of a test — in the same form you would write it in a separate file. A regular "..." literal must fit on one source line, so before Java 15 multi-line text had to be glued together from pieces.

SQL queries in DAO classes and test data gain the most:

String sql = """
        SELECT o.id, o.total, c.name
        FROM orders o
        JOIN customers c ON c.id = o.customer_id
        WHERE o.status = 'PAID'
        ORDER BY o.created_at DESC
        """;

You can copy the query into a database console and back without touching it. With concatenation, the space at the joint between pieces keeps getting lost: "FROM orders" + "WHERE ..." produces ordersWHERE and an SQL syntax error that only shows up at run time.

A text block does not change how the string is stored or compared. It is immutable like any String (see String immutability) and goes into the string pool like any literal.

Syntax: opening and closing delimiters

A text block starts with three double quotes """, followed by nothing but optional spaces up to the end of the line, and then a mandatory line break. The content starts on the next source line. The block ends with three quotes — either on a line of their own or right after the last character of the text.

You can't write a text block on a single line. This is the most common mistake for people coming from Python or Kotlin, where """Hello""" is perfectly fine:

String s = """Hello""";

// error: illegal text block open delimiter sequence, missing line terminator

Spaces after the opening delimiter are allowed and don't end up in the result:

String s = """
        abc""";   // three spaces after """ on the first line

System.out.println(s); // abc

An empty text block is possible too: if the closing quotes sit on the line right after the opening ones, you get an empty string.

String empty = """
        """;
System.out.println(empty.isEmpty()); // true

How the compiler strips indentation

The compiler removes the common indentation of a text block — the leading whitespace that all content lines share. It finds the line with the fewest leading whitespace characters and cuts exactly that many characters from every line. This whitespace is called incidental: it comes from formatting the Java code, not from the text itself.

String html = """
        <ul>
            <li>Java</li>
        </ul>
        """;

// Result: "<ul>\n    <li>Java</li>\n</ul>\n"

The <ul> and </ul> lines have 8 spaces, the <li> line has 12. The minimum is 8, so <li> keeps its extra 4 spaces: relative indentation inside the text survives. Shift the whole block left or right along with the code and the result stays the same.

When looking for the minimum, the compiler takes into account:

  • every non-blank content line;
  • the closing delimiter line, if it contains nothing but whitespace and """.

Empty lines and lines made only of whitespace don't count and become empty in the result. That's why an empty line inside a block doesn't reset the indentation to zero:

String s = """
        a

        b
        """;
// Result: "a\n\nb\n"

Closing delimiter position: indentation and the trailing newline

The position of the closing """ decides two things: whether the string ends with \n and how many spaces stay on the left. If the quotes are on a line of their own, the last line break is part of the result. If they are shifted left of the text, that difference becomes the indentation of every line.

String a = """
        Hello
        World""";           // "Hello\nWorld"

String b = """
        Hello
        World
        """;                // "Hello\nWorld\n"

String c = """
        Hello
        World
    """;                    // "    Hello\n    World\n"

String d = """
        Hello
        World
                """;        // "Hello\nWorld\n"
Where the closing """ is Trailing newline Left indentation
Right after the text (a) No Stripped down to the leftmost text line
On its own line, aligned with the text (b) Yes Stripped down to the leftmost text line. The most common choice
On its own line, left of the text (c) Yes The gap between the text and the quotes stays — 4 spaces here
On its own line, right of the text (d) Yes Same as b: the text sets the minimum, quotes further right change nothing

Option c is the standard way to keep indentation on the whole text, for example when a YAML or HTML fragment will be embedded in another document. You can't add indentation by pushing the closing quotes to the right: string d equals b. That's what the indent() method is for.

If you want no trailing newline but still prefer the closing quotes on their own line, end the last line with a backslash (more on this in the escape sequences section):

String s = """
        Hello
        World\
        """;                // "Hello\nWorld"

Trailing spaces and mixing tabs with spaces

The compiler silently removes spaces at the end of every line in a text block. This is deliberate: editors and git often add or trim trailing whitespace without anyone noticing, and the literal shouldn't change because of that. If you do need a trailing space — say, for a fixed-width text format — write it as the \s escape or the octal code \040:

String s = """
        red
        green\s
        blue\040\040
        """;
// "red   " in the source — with three trailing spaces
// Result: "red\ngreen \nblue  \n"

The second gotcha is the tab character. The compiler counts indentation in characters, not in screen columns: a tab and a space weigh the same, one character each. If one line starts with a tab plus four spaces and another with twelve spaces, they may look aligned in the editor, but the minimum indentation turns out to be 5 characters:

String m = """
→   tab
            space
            """;
// → is a tab character followed by 4 spaces; the other lines have 12 spaces each
// Result: "tab\n       space\n" — the second line keeps 7 spaces

The -Xlint:text-blocks compiler option catches both cases with the warnings [text-blocks] inconsistent white space indentation and [text-blocks] trailing white space will be removed. Turn it on in your build if the project uses text blocks a lot.

Easy to miss

A tab written as the \t escape at the start of a line doesn't affect the indentation calculation: escape sequences are translated only after the indentation is removed. A block with the single line \tX produces a tab character, X and \n.

Escape sequences: quotes, \s and the \ line continuation

All the escape sequences of regular strings work in a text block (\n, \t, \", \\, \uXXXX and the rest), and single or double quotes inside don't need escaping. Only three quotes in a row must be escaped — otherwise the compiler takes them for the end of the block. Text blocks also brought two new escapes: \s and \<line-terminator>.

String q = """
        She said "hi"
        Java: \"""text block\"""
        Also ""\" works
        """;
System.out.print(q);
// She said "hi"
// Java: """text block"""
// Also """ works

Without escaping, the line Java: """text block""" ends the block at the first three quotes, and the compiler reports error: ';' expected. Escaping any one of the three quotes is enough: \""" and ""\" work the same way.

A backslash at the end of a line is the \<line-terminator> escape: the line break is dropped and the next source line is joined to the current one. This lets you split a long single-line string across several lines of code:

String sql = """
        SELECT id, name \
        FROM users \
        WHERE active = 1""";
// "SELECT id, name FROM users WHERE active = 1"

The space before \ is kept: it's no longer trailing, since the backslash follows it on the line.

Written as Produces Where it works
" and "" The quotes themselves, no escaping needed Text blocks only
\""" or ""\" Three quotes in a row inside the block Text blocks only
\<line-terminator> Joins the source line with the next one, no \n added Text blocks only
\s A single space (U+0020) that won't be stripped as trailing Text blocks and regular strings (Java 15+)
\n, \t, \\, \040, A Same as in a regular string Everywhere

A backslash in a text block is escaped just like in a regular string, so the regular expression \d+\.\d+ is still written as \\d+\\.\\d+. Java has no raw string literals that skip escape processing. For more on regular expressions, see Regular Expressions in Java.

Line endings: always \n

Every line break inside a text block becomes \n (LF), even if the source file is saved on Windows with CRLF (\r\n) line endings. The compiler normalizes line terminators, so the same code produces the same string on any OS and with any git settings.

String s = """
        x
        y
        """;
System.out.println(s.contains("\r")); // false — on any OS

If an external system needs the platform's line endings, replace them explicitly: s.replace("\n", System.lineSeparator()). If you need exactly \r\n (HTTP and SMTP, for example), put the \r escape at the end of each line in the block.

The order in which a text block is processed

The compiler turns a text block into a string in three steps, and their order explains almost every surprising case:

  1. Line terminators \r\n and \r are replaced with \n.
  2. The common leading indentation and the trailing spaces of each line are removed.
  3. Escape sequences are translated: \n, \t, \s, \", \<line-terminator> and the rest.

Because escapes are translated last, a \n inside a line doesn't create a new line for the indentation calculation, and \s or \040 survive trailing-space removal — at step 2 they are still the plain characters \ and s:

String s = """
        a\nb
          c
        """;
// Result: "a\nb\n  c\n"
// \n split the first line in two, but the indentation of "  c" is measured against "a\nb"

The API mirrors the same steps: String.stripIndent() does step 2, and String.translateEscapes() does step 3.

Inserting values: formatted() instead of interpolation

Text blocks have no variable interpolation like ${name}: a text block is a constant computed at compile time. To insert values, use the formatted() method (Java 15), which works like String.format() but is called on the template itself:

String html = """
        <p>Hello, %s! You have %d new messages.</p>
        """.formatted("Anna", 3);

System.out.print(html); // <p>Hello, Anna! You have 3 new messages.</p>

The %s, %d, %.2f specifiers and the choice between formatted(), String.format() and printf() are covered in String Formatting in Java. For one or two values, replace("{name}", name) works too. For SQL, never put values into the text at all — use PreparedStatement parameters, otherwise you get SQL injection.

String Templates (STR."Hello \{name}") were a preview feature in Java 21 and 22, but were removed from the language in Java 23. In current Java versions, formatted() is still the way to insert values.

String methods for text blocks: stripIndent(), translateEscapes(), indent()

Alongside text blocks, String got methods that perform the same processing at run time — for strings read from a file or received from outside. A text block itself doesn't need them: the compiler has already done the work.

Method What it does Example and result
stripIndent() (Java 15) Removes common indentation and trailing spaces using the compiler's algorithm " a\n b\n c".stripIndent() → "a\n b\nc"
translateEscapes() (Java 15) Turns escape sequences written as text into the actual characters "Tab:\\tEnd".translateEscapes() → a string with a real tab
formatted(Object...) (Java 15) Inserts values, like String.format(this, args) "%d%%".formatted(5) → "5%"
indent(int n) (Java 12) Adds (n > 0) or removes (n < 0) n spaces at the start of each line and ends every line with \n "a\nb\n".indent(2) → " a\n b\n"
lines() (Java 11) Returns a Stream<String> of lines without line terminators "one\ntwo\nthree\n".lines().count() → 3

translateEscapes() is handy when escape sequences arrive as text — for example, from a config file that contains Hello\nWorld with a real backslash. An unknown sequence such as \x throws IllegalArgumentException: Invalid escape sequence. So does \uXXXX: Unicode escapes are handled only by the compiler, before lexical analysis, and translateEscapes() doesn't support them.

A text block is a constant: ==, case labels and annotations

A text block is a string literal just like "...": it's a constant expression, evaluated at compile time and interned in the string pool. So a text block and a regular literal with the same content are the same object:

String h1 = "hello\n";
String h2 = """
        hello
        """;
System.out.println(h1 == h2);      // true — one object from the string pool
System.out.println(h1.equals(h2)); // true

Don't rely on == for strings in real code anyway — Comparing strings explains why. The practical benefit of being a constant is that a text block can go anywhere a constant is required: a case label, an annotation value, a static final field.

switch ("OK") {
    case """
         OK""" -> System.out.println("case matched");
    default -> System.out.println("default");
}
// case matched

Once you call a method on a text block (formatted(), strip()), the result is no longer a constant: the string is created at run time and isn't allowed in a case label.

Does it compile? Text blocks in OCP-style questions

The OCP exam (1Z0-830) tests text blocks with short snippets: does the declaration compile, and what exactly ends up in the string. Try to answer yourself before reading the breakdown.

// 1
String s1 = """abc""";

// 2
String s2 = """
    abc""";

// 3
String s3 = """
    a \
    """;

// 4
String s4 = """
    ab
      c
    """;
System.out.println(s4.length());

// 5
String s5 = """
    I said: """Hi"""
    """;
  1. Doesn't compile. A line break is required after the opening """: illegal text block open delimiter sequence, missing line terminator.
  2. Compiles, s2 is "abc": the quotes follow the text directly, so there's no trailing newline.
  3. Compiles, s3 is "a ": \ drops the line break, and the space before it isn't trailing, so it stays.
  4. Prints 7: the string is "ab\n c\n" — 2 + 1 + 3 + 1 characters. The c line keeps 2 spaces of relative indentation.
  5. Doesn't compile: the first three quotes inside the text close the block. You need \"""Hi\""".

Frequently asked questions

Which Java version supports text blocks?

Java 15 and later, with no extra flags. In Java 13 and 14 they were a preview feature and needed --enable-preview to compile and run. Java 8 and 11 don't have text blocks at all: such code won't compile, and for multi-line text you're left with concatenation, String.join("\n", ...) or reading a resource file.

Is a text block slower than a regular string?

No. Indentation, trailing spaces and escape sequences are processed at compile time, and the class file gets an ordinary string constant — the same one a "..." literal with \n would produce. There's no difference at run time.

How are Java text blocks different from triple quotes in Python or Kotlin?

In Java a line break is required after the opening """, indentation is stripped automatically (Kotlin needs a trimIndent() call for that), and there's no variable interpolation — values go in through formatted(). It isn't a raw string either: a backslash still escapes the next character. Details are in the escape sequences section.

How do I convert a concatenated string into a text block in IntelliJ IDEA?

Put the caret on the string literal, press Alt+Enter and choose "Replace with text block". IDEA merges the pieces joined with + into one block and drops the unnecessary \n and \". It works when the project language level is 15 or higher.

Comments

Please log in or register to have a possibility to add comment.