Basics

10. Text Blocks

Text blocks ("""...""") provide multi-line string literals that automatically strip common leading whitespace (incidental whitespace), making embedded JSON, SQL, and HTML readable.

Java 15+ (standard)

Explanation

Text blocks (JEP 378, standard in Java 15) are delimited by """. The content begins after the newline following the opening """. The closing """ position determines how much leading whitespace is considered "incidental" and stripped โ€” the compiler removes the whitespace that is common to all lines (including the closing delimiter's indentation).

The resulting string contains \n line endings regardless of the OS. You can use \ at the end of a source line to suppress a newline (continuation). Text blocks support all the same escape sequences as regular strings, plus \s (explicit space, prevents trailing whitespace trimming) and \<line-terminator> (line continuation).

Text blocks do not change string identity rules โ€” they are still interned string literals.

Example

public class TextBlocks {
    public static void main(String[] args) {
        // Without text blocks: escaping is painful
        String jsonOld = "{\n" +
                "  \"name\": \"Alice\",\n" +
                "  \"age\": 30\n" +
                "}";

        // With text blocks: clean and readable
        String json = """
                {
                  "name": "Alice",
                  "age": 30
                }
                """;

        System.out.println(json);

        // SQL example
        String query = """
                SELECT u.name, o.total
                FROM users u
                JOIN orders o ON u.id = o.user_id
                WHERE u.active = true
                ORDER BY o.total DESC
                """;
        System.out.println(query);

        // Line continuation with \
        String singleLine = """
                Hello \
                World""";
        System.out.println(singleLine); // "Hello World" (no newline in between)

        // formatted() works with text blocks
        String html = """
                <p>Hello, %s!</p>
                """.formatted("Java");
        System.out.println(html);
    }
}

Sources