00:00

Text Blocks in Java (Standard Since Java 15)

Last updated: · Standard since Java 15

A text block is a multi-line string literal written between triple double quotes ("""). It keeps line breaks and quotes as you type them and removes common indentation. Text blocks were previewed in Java 13 and 14 and became standard in Java 15 (JEP 378).

This tutorial explains the rules for indentation and line endings, and the escape sequences that give you precise control.

1. Why Were Text Blocks Added?

Embedding SQL, JSON, HTML or XML in Java code used to require + concatenation, \n and \" escapes on every line. The result was hard to read and easy to break. Text blocks let the embedded text look like the real thing.

2. Syntax and Rules

Syntax.java
String query = """
    SELECT *
    FROM customer
    """;   // the opening """ must be followed by a line break
Rule or escapeEffect
Opening """must be followed by a line terminator
Incidental indentationthe common leading whitespace of all lines, including the closing line, is removed
Trailing spacesremoved from every line
\ at line endjoins the line with the next (no newline)
\sa single space that is not stripped
Line endingsalways normalised to \n, whatever the source file uses

3. Practical Examples

Example 1: SQL and JSON

TextBlockBasics.java
public class TextBlockBasics {
    public static void main(String[] args) {
        // The position of the closing """ sets the left margin
        String sql = """
            SELECT id, name, city
            FROM customer
            WHERE city = 'Pune'
            ORDER BY name
            """;
        System.out.print(sql);

        // JSON keeps its quotes without escaping; formatted() fills values
        String json = """
            {
              "order": "%s",
              "items": %d
            }""".formatted("ORD-77", 3);
        System.out.println(json);

        // Same value as the old concatenated version
        String old = "{\n  \"order\": \"ORD-77\",\n  \"items\": 3\n}";
        System.out.println("equal to concatenation: " + json.equals(old));
    }
}
Output
SELECT id, name, city
FROM customer
WHERE city = 'Pune'
ORDER BY name
{
  "order": "ORD-77",
  "items": 3
}
equal to concatenation: true

formatted(), added in Java 15, works like String.format on the text block itself.

Example 2: Escapes and indentation control

TextBlockEscapes.java
public class TextBlockEscapes {
    public static void main(String[] args) {
        // \ at the end of a line joins it with the next (no newline)
        String sentence = """
            Java text blocks remove \
            the need for string concatenation.""";
        System.out.println(sentence);

        // Trailing spaces are stripped; \s keeps one space
        String padded = """
            name\s
            id  \s
            """;
        padded.lines().forEach(l -> System.out.println("[" + l + "]"));

        // Moving the closing delimiter left keeps extra indentation
        String indented = """
                indented line
            """;
        System.out.print("[" + indented.replace("\n", "") + "]\n");

        // Three quotes inside the text need one escape
        String quote = """
            She said \""" hello \""" twice.""";
        System.out.println(quote);
    }
}
Output
Java text blocks remove the need for string concatenation.
[name ]
[id   ]
[    indented line]
She said """ hello """ twice.

4. How the Compiler Processes a Text Block

Text block processing steps The compiler normalises line endings to newline, removes incidental indentation and trailing spaces, and finally interprets escape sequences such as backslash-s. source text between """ ... """ normalise line endings CRLF -> LF strip indentation and trailing spaces process escapes \s, \<newline>, \"
Figure 1: The result is an ordinary String constant; there is no run-time cost.

5. Important Points and Best Practices

  • Place the closing """ on its own line to end the value with a newline; put it after the last text to avoid one.
  • Do not mix tabs and spaces for indentation; the compiler counts each as one whitespace character.
  • Use formatted() or replace() to insert values; never build SQL with user input this way (use prepared statements).
  • A text block is a normal String, so all string methods work on it.

6. Summary

  • Text blocks became standard in Java 15 (JEP 378) and are part of Java 17 LTS.
  • They are written between """ delimiters and span multiple lines.
  • Incidental indentation and trailing spaces are removed automatically.
  • \ and \s escapes control line joins and spaces.

Related Tutorials

7. References