How do I use text blocks to write cleaner multi-line strings?

Text blocks in Java, introduced in Java 15, provide a way to declare multi-line strings in a cleaner and more readable format compared to traditional string concatenation or line breaks (\n). They are enclosed using triple double quotes (""") and support multi-line content without requiring explicit escape characters for formatting.

Key Features of Text Blocks

  1. Multi-line Flexibility: No need for manual concatenation or escape characters, as everything is written as-is.
    String message = """
            Hello,
            This is a multi-line message.
            Regards,
            AI Assistant
            """;
    
  2. Improved Readability: Code looks cleaner, especially for complex templates like JSON, XML, or SQL.

  3. Whitespace Control: Leading and trailing whitespace can be managed easily without affecting the structure.
  4. String Formatting: Text blocks can use the formatted() method for dynamic content injection, similar to String.format.

Examples of Usage for Clean Code

1. Working with JSON or HTML Templates

Instead of concatenating strings for JSON, text blocks help preserve structure:

String jsonTemplate = """
       {
           "username": "%s",
           "email": "%s"
       }
       """;
String json = jsonTemplate.formatted("foo", "[email protected]");
System.out.println(json);

2. Complex SQL Queries

Writing SQL in code often spreads across multiple lines. With text blocks:

String query = """
       SELECT id, username, email
       FROM users
       WHERE email = '%s'
       ORDER BY username;
       """.formatted("[email protected]");

This improves readability compared to a mix of + or \n.

3. HTML Documents

String html = """
       <html>
           <head>
               <title>%s</title>
           </head>
           <body>
               <h1>Welcome, %s!</h1>
           </body>
       </html>
       """.formatted("My Page", "Visitor");

Additional Tips

  1. Formatting Whitespace Correctly: Text blocks remove unnecessary leading indentation (common with code). However, if needed, you can align whitespaces manually:
    String alignedBlock = """
            A line of text
            More text with consistent indentation
            """;
    
  2. Escape Sequences: Although text in text blocks is written as-is, you can still use escape sequences where necessary:
    String code = """
           public static void main(String[] args) {
               System.out.println("Hello, World!");
           }
           """;
    
  3. Dynamic Injection: Combine text blocks with .formatted() for cleaner parameterized content:
    String greeting = """
            Dear %s,
    
            Thank you for your email (%s). 
            We will get back to you shortly.
            """.formatted("John", "[email protected]");
    

Benefits Over Traditional Strings

  • Enhanced readability for configurations or templates.
  • Less boilerplate—no need for multiple +, \n, or explicit escapes.
  • Ideal for structured data like SQL, HTML, JSON, etc.

How to Use Java 17 Text Blocks for Multiline Strings

Java 17 introduced text blocks to simplify the use of multiline strings, making it much easier to include and manage multiline text in your Java applications. Text blocks were actually introduced in Java 15 but were further refined and are fully supported in Java 17.

What Are Text Blocks?

A text block is a multiline string literal declared with triple double-quotes ("""). It preserves the format of the text, including newlines and whitespace, making it ideal for creating strings like XML, JSON, HTML, SQL queries, or large blocks of text.


Syntax and Usage

Here’s the basic syntax:

String multilineString = """
        Line 1
        Line 2
        Line 3
        """;

Key Features of Text Blocks:

  1. Multiline Strings: Text blocks support strings spanning multiple lines.
  2. Automatic Line Breaks: No need to write \n at the end of each line.
  3. Automatic Handling of Whitespace: Leading whitespace can be trimmed automatically.
  4. Readable for Formats: Excellent for embedding JSON, SQL, XML, or other text-based formats.

Example Usages

1. JSON or XML Example

String json = """
        {
            "name": "John Doe",
            "age": 30,
            "city": "New York"
        }
        """;

System.out.println(json);

2. SQL Query Example

String sql = """
        SELECT *
        FROM users
        WHERE age > 18
          AND city = 'New York';
        """;

System.out.println(sql);

3. Embedding an HTML Template

String html = """
        <html>
            <body>
                <h1>Hello, World!</h1>
                <p>This is an example of a text block.</p>
            </body>
        </html>
        """;

System.out.println(html);

Notes on Formatting and Indentation

  1. Indentation Control: Java automatically determines the minimum level of indentation for the text block and removes it by default.

    For example:

    String indentedText = """
              This text block
              is indented uniformly.
              """;
    

    Outputs:

    This text block
    is indented uniformly.
    

    Notice that the leading spaces are omitted while retaining the structure.

  2. Custom Alignment: To maintain a consistent indentation in your block while coding, Java aligns the text block based on the whitespace before the ending triple quotes.


Escape Characters in Text Blocks

Text blocks still support escape sequences just like regular strings:

  • \n: Newline
  • \t: Tab
  • \": Double quote if needed inside the block
  • \\: Backslash

Example:

String special = """
        She said, \"Hello!\"
        This includes some escape sequences: \\n \\t
        """;

System.out.println(special);

Summary

Text blocks are a powerful feature, making it easier to embed multiline strings. They reduce the need for concatenation and enhance readability. Whether you’re working with configurations, templates, or queries, they provide a neat and concise way to manage strings in Java applications.

Best Practices

  • Use text blocks instead of concatenated strings for multiline text.
  • Rely on proper indentation to make the code more readable.
  • Test the output when using text blocks with external sources like JSON, SQL, or XML to ensure correctness.

Happy coding! 😊