Modern Java Feature: Text Blocks

Java developers have long struggled with multi-line strings containing escaped characters and awkward formatting. Enter Text Blocks, a modern Java feature that makes multi-line string handling cleaner, more readable, and more expressive.

๐Ÿ†• What Is a Text Block?

A text block is a multi-line string literal introduced as a preview in Java 13 and officially added in Java 15. It allows you to write strings across multiple lines without having to escape every newline or quote.

Syntax

Text blocks are enclosed in three double quotes ("""), and must start on a new line:

String html = """
    <html>
        <body>
            <h1>Hello, World!</h1>
        </body>
    </html>
    """;

This is far more readable than:

String html = "<html>\n" +
              "    <body>\n" +
              "        <h1>Hello, World!</h1>\n" +
              "    </body>\n" +
              "</html>\n";

Where Can You Use a Text Block?

Anywhere you can use a regular string, you can use a text block. That includes:

  • Assignments to variables

  • Method arguments

  • Return values

  • Annotations

  • Logs and templates

System.out.println("""
    This is a valid
    text block string
    used as an argument.
    """);

Text blocks shine when dealing with structured or long-form content:

  • ๐Ÿ–ฅ๏ธ HTML/XML/JSON snippets

  • ๐Ÿ’พ SQL queries

  • ๐Ÿค– Prompt engineering for AI

  • ๐Ÿง‘โ€๐Ÿซ Code samples for documentation

  • ๐Ÿ“œ Poetry, song lyrics, or long messages

String sql = """
    SELECT id, name
    FROM users
    WHERE active = 1
    ORDER BY name;
    """;

Smart Whitespace Handling: Incidental vs Essential

One of the most powerful features of text blocks is their ability to remove incidental white spaceโ€”the indentation that's not part of the string itself but exists to align with your code.

Letโ€™s visualize this with ยท characters to represent leading spaces.

๐Ÿ‘‡ Example: Incidental White Space Removed

void writeHTML() {
    String html = """
ยทยทยทยทยทยทยทยท<html>
ยทยทยทยทยทยทยทยท    <body>
ยทยทยทยทยทยทยทยท        <p>Hello World.</p>
ยทยทยทยทยทยทยทยท    </body>
ยทยทยทยทยทยทยทยท</html>
ยทยทยทยทยทยทยทยท""";
    writeOutput(html);
}

โœ… The output of html becomes:

<html>
    <body>
        <p>Hello World.</p>
    </body>
</html>

Java determines the minimum indentation level (based on the closing delimiter position) and removes it from all lines. This keeps your string readable and aligned with your code.

Preserving Essential White Space

To preserve indentation within the string, just move your content to the right:

void writeHTML() {
    String html = """
ยทยทยทยทยทยทยทยท    <html>
ยทยทยทยทยทยทยทยท        <body>
ยทยทยทยทยทยทยทยท            <p>Hello World.</p>
ยทยทยทยทยทยทยทยท        </body>
ยทยทยทยทยทยทยทยท    </html>
ยทยทยทยทยทยทยทยท""";
    writeOutput(html);
}

Result:

    <html>
        <body>
            <p>Hello World.</p>
        </body>
    </html>

Opting Out of Trimming Entirely

If you donโ€™t want Java to trim anything, place the closing delimiter on the far left:

void writeHTML() {
    String html = """
                  <html>
                      <body>
                          <p>Hello World.</p>
                      </body>
                  </html>
""";
    writeOutput(html);
}

Java will treat every character as-is, preserving all leading spaces.

For all the nitty-gritty details, see JEP 355.


Normalize Line Terminators

Text blocks use \n (line feed) as the default line terminator on all platforms. If you need to convert them to your system-specific line separator (e.g. \r\n on Windows), you can do:

String adjusted = textBlock.replaceAll("\n", System.lineSeparator());

This ensures your strings behave consistently across environments.


New String Methods Introduced

Java 15 introduced several useful methods in the String class to complement and enhance the text block feature:

MethodDescription
stripIndent()Removes incidental indentation from a multi-line string
translateEscapes()Converts escape sequences like \\n or \\t into actual characters
formatted(Object...)A more readable alternative to String.format(), used directly on string instances

Example: ๐Ÿ“„ formatted(...) with Text Blocks

You can use .formatted(...) directly on a text block to inject dynamic values:

String email = """
    Dear %s,

    Your order #%d has been shipped and is expected to arrive by %s.

    Thank you for shopping with us!
    """.formatted("Mirna", 12345, "Friday");

System.out.println(email);

Output:

Dear Mirna,

Your order #12345 has been shipped and is expected to arrive by Friday.

Thank you for shopping with us!

This makes text blocks a great fit for templated emails, prompts, or code generation โ€” with clean syntax and no clutter.

๐Ÿ“š Official Documentation

Want to learn more or see additional examples? Check out the official guide:
๐Ÿ‘‰ Text Blocks in Java 15

Conclusion

Text blocks are a small yet powerful improvement in Java that makes your code easier to read, write, and maintainโ€”especially when working with structured or formatted content.

No more escaping newlines or cramming everything into one line. Just write clean, readable text!

๐Ÿงญ Stay tuned for more in the Modern Java Features series!

0
Subscribe to my newsletter

Read articles from Mirna De Jesus Cambero directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mirna De Jesus Cambero
Mirna De Jesus Cambero

Iโ€™m a backend software engineer with over a decade of experience primarily in Java. I started this blog to share what Iโ€™ve learned in a simplified, approachable way โ€” and to add value for fellow developers. Though Iโ€™m an introvert, Iโ€™ve chosen to put myself out there to encourage more women to explore and thrive in tech. I believe that by sharing what we know, we learn twice as much โ€” thatโ€™s precisely why Iโ€™m here.