Text Blocks are a modern Java feature that makes it easier to write multi-line strings. They are especially useful for HTML, SQL, JSON, and formatted text.
"""A text block starts and ends with three double quotes. The content inside is treated as a multi-line string.
// Basic syntax of a Java text block
String message = """
Hello World
Welcome to Java Text Blocks
Enjoy clean multi-line strings
""";
Switch between the toggle to see why Text Blocks are a game changer for JSON data!
// ❌ The Messy Way: Escaping Hell
String json = "{\n" +
" \"name\": \"John\",\n" +
" \"age\": 30,\n" +
" \"city\": \"New York\"\n" +
"}";
// Using text blocks for HTML content
String html = """
Hello JavaThis is a text block example
"""; System.out.println(html);
The output prints the HTML exactly as written, including line breaks and indentation. This makes text blocks ideal for templates and structured content.