← Back to Chapters

Java Text Blocks

? Java Text Blocks

? Quick Overview

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.

? Key Concepts

  • Introduced in Java 15
  • Uses triple double-quotes """
  • Preserves line breaks and formatting
  • Improves readability of long strings

? Syntax & Theory

A text block starts and ends with three double quotes. The content inside is treated as a multi-line string.

? View Code Example
// Basic syntax of a Java text block
String message = """
Hello World
Welcome to Java Text Blocks
Enjoy clean multi-line strings
""";

⚡ Visualizer: JSON Data

Switch between the toggle to see why Text Blocks are a game changer for JSON data!

Old Way (Java 14) New Way (Text Blocks)
// ❌ The Messy Way: Escaping Hell
String json = "{\n" +
              "  \"name\": \"John\",\n" +
              "  \"age\": 30,\n" +
              "  \"city\": \"New York\"\n" +
              "}";

▶️ Code Example

? View Code Example
// Using text blocks for HTML content
String html = """

Hello Java

This is a text block example

"""; System.out.println(html);

?️ Live Output / Explanation

The output prints the HTML exactly as written, including line breaks and indentation. This makes text blocks ideal for templates and structured content.

? Tips & Best Practices

  • Use text blocks for long, readable strings
  • Avoid unnecessary escape characters
  • Keep indentation consistent
  • Best for SQL, JSON, XML, and HTML

? Try It Yourself

  • Create a text block for an SQL query
  • Store JSON data using text blocks
  • Compare normal strings vs text blocks