javabeginner

Text Blocks — Multi-line Strings

Use Java text blocks for readable multi-line strings: SQL, JSON, HTML, and formatted templates.

java
public class TextBlocks {
    // SQL query
    static String query = """
            SELECT u.name, u.email, COUNT(o.id) AS order_count
            FROM users u
            LEFT JOIN orders o ON u.id = o.user_id
            WHERE u.status = 'active'
              AND u.created_at > ?
            GROUP BY u.name, u.email
            HAVING COUNT(o.id) > 5
            ORDER BY order_count DESC
            """;

    // JSON template
    static String jsonTemplate(String name, String email) {
        return """
                {
                    "name": "%s",
                    "email": "%s",
                    "role": "user",
                    "active": true
                }
                """.formatted(name, email);
    }

    // HTML
    static String html = """
            <html>
                <head><title>Report</title></head>
                <body>
                    <h1>Monthly Report</h1>
                    <p>Generated at: %s</p>
                </body>
            </html>
            """;

    // Regex pattern
    static String emailRegex = """
            ^[a-zA-Z0-9._%+-]+\
            @[a-zA-Z0-9.-]+\
            \\.[a-zA-Z]{2,}$""";

    public static void main(String[] args) {
        System.out.println(query);
        System.out.println(jsonTemplate("Alice", "alice@test.com"));

        // String methods with text blocks
        String csv = """
                name,age,city
                Alice,30,NYC
                Bob,25,LA
                """;
        csv.lines()
           .skip(1) // skip header
           .map(line -> line.split(","))
           .forEach(parts -> System.out.printf("%s is %s%n", parts[0], parts[1]));
    }
}

Use Cases

  • Embedding SQL queries in Java code
  • JSON and HTML template strings
  • Readable multi-line configuration strings

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.