⚡IntermediateModern Java

Text Blocks

Write multi-line string literals cleanly using text blocks (Java 15+), without escape sequences and string concatenation.

Overview

Text blocks (Java 15+) are multi-line string literals enclosed in triple double-quotes. They eliminate the need for escape sequences, string concatenation, and manual newlines in multi-line strings. Text blocks are useful for embedding JSON, HTML, SQL, XML, and any other structured text directly in Java code. The indentation of the closing triple-quote determines how much leading whitespace is stripped from each line. Text blocks produce a regular String at runtime, so all String methods work on them.

Key Points

  • •Text block syntax: """ followed by a newline, content, then """
  • •The opening """ must be followed by a newline (cannot be on the same line as content)
  • •The closing """ sets the indentation baseline: common leading whitespace is removed
  • •Trailing whitespace on each line is stripped by default
  • •Result is a regular String; all String methods apply
  • •Use \n for intentional embedded newlines, \s to preserve trailing space
  • •String.formatted() works on text blocks: "Hello %s".formatted(name)
  • •Escape sequences like \t, \n, \\ still work inside text blocks

Examples

Basic text block

public class Main {
    public static void main(String[] args) {
        // Old style: messy escape sequences and concatenation
        String oldJson = "{\n" +
            "  \"name\": \"Alice\",\n" +
            "  \"age\": 30\n" +
            "}";

        // Text block: clean and readable
        String json = """
                {
                  "name": "Alice",
                  "age": 30
                }
                """;

        System.out.println(json);
        System.out.println("Length: " + json.length());
        System.out.println("Is String: " + (json instanceof String));
    }
}

The common indentation (the spaces before {) is stripped automatically. The closing """ on its own line includes a final newline. Move the closing """ to the last line of content to omit the trailing newline.

Text blocks with formatting and embedded values

public class Main {
    record User(String name, int age, String email) {}

    public static void main(String[] args) {
        var user = new User("Bob", 25, "bob@example.com");

        // String.formatted() with text block
        String json = """
                {
                  "name": "%s",
                  "age": %d,
                  "email": "%s"
                }
                """.formatted(user.name(), user.age(), user.email());

        System.out.println(json);

        // HTML template
        String html = """
                <html>
                  <body>
                    <h1>Hello, %s!</h1>
                    <p>Age: %d</p>
                  </body>
                </html>
                """.formatted(user.name(), user.age());

        System.out.println(html);
    }
}

Text blocks support formatted() for substitution. The %s and %d placeholders work just like in String.format(). This is cleaner than concatenating strings across multiple lines.

SQL and multiline strings with text blocks

public class Main {
    public static void main(String[] args) {
        String tableName = "users";
        int minAge = 18;

        // SQL query as text block
        String sql = """
                SELECT id, name, email
                FROM %s
                WHERE age >= %d
                  AND active = true
                ORDER BY name ASC
                """.formatted(tableName, minAge);

        System.out.println("Query:");
        System.out.println(sql);

        // Closing """ position controls trailing newline
        String noTrailingNewline = """
                line one
                line two"""; // closing """ on content line: no trailing newline

        String withTrailingNewline = """
                line one
                line two
                """; // closing """ on its own line: trailing newline included

        System.out.printf("no trailing: [%s]%n", noTrailingNewline);
        System.out.printf("with trailing: [%s]%n", withTrailingNewline);
    }
}

When the closing """ is on the same line as the last content, no trailing newline is added. When it is on its own line, a trailing newline is included.

Common Mistakes

  • Putting content on the same line as the opening """. The first line after the opening triple-quote is a newline; content must start on the next line
  • Forgetting that indentation is relative to the closing """. If the closing """ is indented by 16 spaces, 16 spaces are stripped from each content line
  • Using text blocks for very short single-line strings. For a one-liner, a regular string literal is more readable

Note

In IntelliJ IDEA, you can convert a regular String concatenation to a text block with a single refactoring action. Look for the yellow lightbulb on a multi-line string.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What is the result type of a text block in Java?