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 do I format strings with String::formatted?

The String::formatted method in Java is a concise way to format strings using placeholders, similar to the String::format method but with a cleaner syntax. It was introduced in Java 15, and it allows you to replace placeholders in a string with specified values.

The syntax of the formatted method is straightforward:

String formattedString = "Your name is %s and your age is %d".formatted("John", 25);

Here’s how it works:

  1. The placeholders in the string (such as %s, %d) follow the same format specifiers as used in String.format().
    • %s: Formats strings.
    • %d: Formats integers.
    • %f: Formats floating-point numbers.
    • And so on.
  2. The formatted() method takes the format arguments in the exact order of appearance of the placeholders.

Example Usage:

Here are a few examples illustrating the different use cases:

Example 1: Format a simple text

String result = "Hello, %s!".formatted("Alice");
System.out.println(result);
// Output: Hello, Alice!

Example 2: Combine multiple placeholders

String summary = "Product: %s, Quantity: %d, Price: $%.2f".formatted("Widget", 10, 9.99);
System.out.println(summary);
// Output: Product: Widget, Quantity: 10, Price: $9.99

Example 3: Use with text blocks

In text blocks, you can similarly use the formatted method to insert values dynamically:

String jsonTemplate = """
    {
        "name": "%s",
        "age": %d,
        "email": "%s"
    }
    """;

String json = jsonTemplate.formatted("John", 30, "[email protected]");
System.out.println(json);
// Output:
// {
//     "name": "John",
//     "age": 30,
//     "email": "[email protected]"
// }

Key Points:

  • The formatted method is directly callable on the string you want to format, making the code cleaner.
  • It has the same capabilities as String.format, so it supports all format specifiers.
  • formatted works particularly well with text blocks for clean and readable multi-line string formatting.

This method is helpful for writing concise and fluent code without the need to call String.format explicitly.