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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.