0
0
JavaConceptBeginner · 3 min read

What is Text Block in Java: Simple Explanation and Example

A text block in Java is a way to write multi-line strings easily using triple double quotes """. It preserves the format and line breaks without needing escape characters, making code cleaner and more readable.
⚙️

How It Works

Think of a text block like a window that lets you write a paragraph exactly as you see it, including line breaks and spaces, without adding extra symbols. Instead of using many quotes and escape characters for new lines or quotes inside the string, you just wrap your text in triple double quotes """.

This feature was introduced in Java 13 as a preview feature and standardized in Java 15 to make handling long strings, like JSON or HTML, simpler and less error-prone. The Java compiler automatically keeps the formatting inside the text block, so your string looks just like the text you typed.

💻

Example

This example shows how to create a multi-line string using a text block and print it exactly as written.

java
public class TextBlockExample {
    public static void main(String[] args) {
        String poem = """
            Roses are red,
            Violets are blue,
            Java text blocks
            Make strings easy to do.
            """;
        System.out.println(poem);
    }
}
Output
Roses are red, Violets are blue, Java text blocks Make strings easy to do.
🎯

When to Use

Use text blocks when you need to write strings that span multiple lines, such as HTML, JSON, SQL queries, or formatted text. They help keep your code clean and easy to read by avoiding many escape characters and string concatenations.

For example, if you are embedding a snippet of HTML or a JSON object in your Java code, text blocks let you write it naturally, just like you would in a text editor.

Key Points

  • Text blocks use triple double quotes """ to define multi-line strings.
  • They preserve line breaks and spaces as typed.
  • Introduced in Java 13 as a preview feature and standardized in Java 15 to simplify writing long strings.
  • Useful for embedding formatted text like HTML, JSON, or SQL.
  • Improves code readability by reducing escape characters.

Key Takeaways

Text blocks let you write multi-line strings easily using triple double quotes.
They keep the original formatting, including line breaks and spaces.
Use them to embed formatted text like HTML or JSON in your Java code.
Text blocks improve readability by reducing the need for escape characters.
This feature is available starting from Java 13 as a preview and standardized in Java 15.