Java text blocks explained: multiline strings in Java

Text blocks let you write JSON, SQL, HTML and LLM prompts in Java exactly as they look, without escaped quotes or \n on every line. Here is the syntax, how Java decides what indentation to keep, the two escapes worth knowing, and how to fill in values.

Left, a tilted sheet labelled before, escapes and plus: a JSON string built from several lines joined with plus signs, every quote escaped and every line ending in backslash n, all highlighted in red. An arrow points to a yellow sheet labelled text block, Java 15 and later: String json equals triple quote, then the JSON written plainly on its own lines, closed by triple quote. A dashed red line marks the column of the closing quotes, with a note that indentation left of the line is removed.
Fig. 1 — The same JSON string, before and after. Indentation to the left of the closing quotes is removed.

Here’s a small JSON string, written the way Java made us write it for most of its history:

String json = "{\n" +
        "  \"name\": \"Asha\",\n" +
        "  \"role\": \"Architect\"\n" +
        "}";

Every quote escaped, every line ended with \n, every line joined with +. You can’t paste it into a JSON validator, and you can’t easily paste JSON into it. Text blocks fix that:

String json = """
        {
          "name": "Asha",
          "role": "Architect"
        }""";

Both produce exactly the same string. Text blocks were previewed in Java 13 and 14 and became standard in Java 15 (JEP 378), so they’re available in every LTS from Java 17 on, including Java 21.

The syntax

A text block starts with three double quotes """ followed by a line break, and ends with three double quotes:

String sql = """
    SELECT id, name
    FROM employees
    WHERE designation = ?
    """;

The rules:

  • The opening """ must be followed by a new line. """hello""" on one line is a compile error (“illegal text block open delimiter sequence, missing line terminator”).
  • Quotes don’t need escaping. Write "name" as it is.
  • Line breaks are real. Each line ends with \n. Line endings are always normalised to \n, even if the source file uses Windows \r\n.
  • The result is an ordinary String. Same type, same methods. A text block is just a nicer way to write a string literal.

How indentation works

This is the clever part. You want the text block indented to match your Java code, but you don’t want those spaces in the string. Java removes the incidental indentation for you.

The rule: Java finds the least-indented line (counting the line with the closing """ if it’s on its own line) and removes that much leading whitespace from every line.

String sql = """
    SELECT id, name
    FROM employees
    """;
// "SELECT id, name\nFROM employees\n"

Want to keep some indentation in the string? Move the closing """ to the left. It now counts as the least-indented line:

String sql = """
    SELECT id, name
    FROM employees
  """;
// "  SELECT id, name\n  FROM employees\n": two spaces kept on each line

And where you put the closing """ also decides whether the string ends with a new line:

String a = """
    hello
    """;      // "hello\n"   (closing quotes on their own line)

String b = """
    hello""";  // "hello"     (closing quotes right after the text)
“In a text block, the closing quotes are a ruler: everything to their left is code formatting, everything to their right is the string.”

Java also strips trailing spaces from each line, because they’re invisible and usually accidental. That leads to the two escapes below.

Two escapes worth knowing

Java 15 added two escape sequences, mainly for text blocks.

\ at the end of a line: no line break

A backslash at the very end of a line joins it with the next one. Handy for a long sentence you want to wrap in the source but keep on one line in the string:

String message = """
    This is a long sentence that we \
    want on a single line.""";
// "This is a long sentence that we want on a single line."

\s: a space that isn’t stripped

\s is a single space that survives trailing-space stripping. Use it when trailing spaces matter, like fixed-width text:

String colours = """
    red  \s
    green\s
    """;
// "red   \ngreen \n": the spaces before \s are kept too

All the usual escapes (\t, \n, \\) still work. To write three quotes inside a text block, escape one of them: \""".

Filling in values

Text blocks have no built-in interpolation. Use formatted() (Java 15), which works like String.format:

String prompt = """
    You are a helpful support assistant for %s.
    Answer only from the policy below. If it doesn't say, reply "I don't know".

    Policy:
    %s
    """.formatted(companyName, policyText);

That’s a real pattern if you call LLMs from Java (see calling the Ollama API from Java): prompts are long, multi-line, full of quotes, and much easier to read and edit as text blocks.

String templates (STR."Hello \{name}") were previewed in Java 21 as a built-in alternative, but they were withdrawn in Java 23 and aren’t part of Java today. Stick with formatted().

Where text blocks shine

  • JSON in tests, mocks and request bodies.
  • SQL and JPQL queries in repositories.
  • HTML and email templates.
  • LLM prompts and system messages.
  • Expected output in unit tests, compared with assertEquals.
  • Regular expressions and any text full of quotes or backslashes.

For a single short line, a normal string is still simpler.

Common mistakes

Text on the same line as the opening quotes. The opening """ must end its line. Start the content on the next line.

A surprise trailing new line. Closing """ on its own line adds a final \n. If you compare against a string without one, the test fails. Put the closing quotes at the end of the last line instead.

Tabs mixed with spaces. Indentation stripping counts characters, and a tab counts as one. Mixing tabs and spaces in one text block can leave odd indentation. Use spaces only.

Java added a few methods alongside text blocks that are handy on any string:

  • stripIndent() removes incidental indentation, the same way text blocks do.
  • translateEscapes() turns escape sequences written as text (like a backslash followed by n) into the real characters.
  • formatted(...) fills in %s-style placeholders.

Key takeaways

  • A text block is a multiline string between """ and """. Standard since Java 15, so it’s in Java 17 and 21.
  • The opening """ must be followed by a line break; quotes inside need no escaping.
  • Java removes incidental indentation; the closing """ position controls how much and whether there’s a final new line.
  • \ at line end joins lines; \s is a space that’s kept.
  • Use formatted() to insert values, and PreparedStatement for SQL values.

Frequently asked questions

What is a text block in Java?

A multiline string literal written between triple double quotes ("""). It keeps line breaks and lets you write quotes without escaping, which makes JSON, SQL and HTML far easier to read.

Which Java version introduced text blocks?

Text blocks were previewed in Java 13 and 14 and became a standard feature in Java 15 (JEP 378).

How do I add variables to a Java text block?

Call formatted() on the text block, with %s placeholders where the values go, just like String.format. Java has no built-in string interpolation; the string templates preview from Java 21 was withdrawn.

How do I avoid the trailing new line in a text block?

Put the closing """ directly after the last line of text, not on a line of its own.

Is a text block different from a String?

No. A text block produces an ordinary java.lang.String. It’s only a different way of writing the literal in source code.

Back to the overview: all Java 21 features.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.