Text Blocks for Multi-line Strings
Demonstrates Java text blocks for multi-line string literals with proper indentation handling, template formatting, and SQL/JSON/HTML generation.
Code
public class TextBlocksFormatting {
public static void main(String[] args) {
String json = """
{
"name": "Alice",
"age": 30,
"skills": ["Java", "Python"],
"active": true
}
""";
System.out.println("JSON:");
System.out.println(json);
String sql = """
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.active = true
GROUP BY u.name
HAVING COUNT(o.id) > 0
ORDER BY order_count DESC
""";
System.out.println("SQL:");
System.out.println(sql);
String html = """
<div class="card">
<h2>%s</h2>
<p>%s</p>
</div>
""".formatted("Welcome", "Hello, World!");
System.out.println("HTML:");
System.out.println(html);
String indented = """
Line 1
Line 2
Line 3
""".stripIndent();
System.out.println("Stripped: [" + indented + "]");
String escaped = """
Escaped: \"quote\"
Newline: \n is literal
""";
System.out.println(escaped);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.