Introduction
Working with multi-line strings has traditionally been one of the more cumbersome aspects of Java programming. Before Java 15, developers had to concatenate multiple string literals using the + operator, manually insert newline characters (\n), and escape quotation marks (\”). This approach often resulted in code that was difficult to read, write, and maintain.
To solve this problem, Java introduced Text Blocks as a preview feature in Java 13, improved them in Java 14, and officially finalized them in Java 15. Text Blocks provide a clean and readable way to define multi-line string literals without excessive escaping or concatenation.
What are Java Text Blocks?
A Text Block is a multi-line string literal enclosed within three double quotes (“””). Unlike traditional string literals, Text Blocks automatically preserve line breaks and make it easier to write formatted text.
Instead of writing:
String html = "<html>\n" +
"<body>\n" +
"<h1>Welcome</h1>\n" +
"</body>\n" +
"</html>";
You can simply write:
String html = """
<html>
<body>
<h1>Welcome</h1>
</body>
</html>
""";
The second version is significantly cleaner and easier to understand.
Why Use Java Text Blocks?
Text Blocks provide several advantages:
- Improve code readability
- Eliminate string concatenation
- Preserve formatting
- Reduce escaping of quotation marks
- Make HTML, JSON, XML, and SQL easier to write
- Simplify maintenance
- Produce cleaner source code
Syntax
The basic syntax is:
String variable = """
Multiple lines
of text
go here
""";
Notice that:
- Text begins after the opening “””.
- It ends with another “””.
- The closing delimiter is followed by a semicolon.
Simple Example
public class Main {
public static void main(String[] args) {
String message = """
Welcome to Java
Text Blocks Tutorial
Enjoy Learning!
""";
System.out.println(message);
}
}
Output
Text Blocks Tutorial
Enjoy Learning!
Traditional String vs Text Block
Traditional String
String message = "Java\n" +
"Programming\n" +
"Tutorial";
Text Block
String message = """
Java
Programming
Tutorial
""";
The Text Block version is much easier to read.
Example 1: HTML
Without Text Blocks
String html =
"<html>\n" +
"<body>\n" +
"<h1>Hello</h1>\n" +
"</body>\n" +
"</html>";
With Text Blocks
String html = """
<html>
<body>
<h1>Hello</h1>
</body>
</html>
""";
System.out.println(html);
Output
<body>
<h1>Hello</h1>
</body>
</html>
Example 2: JSON
String json = """
{
"id": 101,
"name": "Rahul",
"city": "Delhi"
}
""";
System.out.println(json);
Output
“id”: 101,
“name”: “Rahul”,
“city”: “Delhi”
}
Text Blocks make JSON definitions much cleaner.
Example 3: SQL Query
String query = """
SELECT id,
name,
salary
FROM employee
WHERE salary > 50000
ORDER BY salary DESC;
""";
System.out.println(query);
Output
name,
salary
FROM employee
WHERE salary > 50000
ORDER BY salary DESC;
Writing SQL becomes far more readable.
Example 4: XML
String xml = """
101
Rahul
IT
""";
System.out.println(xml);
Output
<id>101</id>
<name>Rahul</name>
<department>IT</department>
</employee>
Example 5: JavaScript
String script = """
function greet() {
console.log("Welcome");
}
greet();
""";
System.out.println(script);
This is useful in web applications where Java generates JavaScript.
Text Blocks and Quotes
One major advantage is that double quotes usually do not need escaping.
Traditional String
String text = "He said \"Hello\".";
Text Block
String text = """
He said "Hello".
""";
The code is much simpler.
Preserving Indentation
Text Blocks intelligently remove common leading whitespace.
Example
String message = """
Java
Python
C++
""";
System.out.println(message);
Output
Python
C++
Java automatically determines the common indentation and removes it.
Escape Sequences in Text Blocks
Text Blocks still support escape sequences.
Example
String text = """
Line 1
Line 2\tTabbed
Line 3
""";
System.out.println(text);
Output
Line 2 Tabbed
Line 3
Supported escape sequences include:
- \n – New line
- \t – Tab
- \” – Double quote (optional in most cases)
- \\ – Backslash
- \r – Carriage return
Real-Life Example
Suppose you’re developing an online shopping application and need to generate an email template.
String email = """
Dear Customer,
Thank you for your purchase.
Your order has been successfully placed.
Regards,
ABC Store
""";
System.out.println(email)
Instead of multiple concatenated strings, a Text Block keeps the email template readable and maintainable.
Working with String Methods
A Text Block is still a regular String object.
Example
String language = """
Java Programming
""";
System.out.println(language.length());
System.out.println(language.toUpperCase());
System.out.println(language.contains("Java"));
Output
JAVA PROGRAMMING
true
All String methods work exactly the same.
Common Use Cases
Java Text Blocks are commonly used for:
- HTML templates
- JSON payloads
- XML documents
- SQL queries
- GraphQL queries
- REST API request bodies
- Email templates
- Markdown content
- JavaScript snippets
- Configuration files
Benefits of Java Text Blocks
1. Improved Readability
Multi-line text is easier to understand.
2. Less Boilerplate
No string concatenation is required.
3. Fewer Escape Characters
Double quotes usually don’t require escaping.
4. Easier Maintenance
Updating formatted text becomes much simpler.
5. Better Formatting
The source code closely matches the output.
6. Modern Java Feature
Recommended for Java 15 and later.
Traditional Strings vs Text Blocks
| Feature | Traditional String | Text Block |
|---|---|---|
| Multi-line support | Difficult | Easy |
| String concatenation | Required | Not required |
| Readability | Moderate | Excellent |
| Escaping quotes | Frequent | Minimal |
| HTML writing | Complex | Simple |
| JSON writing | Verbose | Clean |
| SQL queries | Hard to read | Easy to read |
| Maintenance | Difficult | Easy |
Best Practices
- Use Text Blocks for multi-line content.
- Keep indentation consistent.
- Use Text Blocks for HTML, JSON, XML, and SQL.
- Avoid unnecessary escape characters.
- Use descriptive variable names.
- Format content for readability.
- Continue using normal string literals for short, single-line text.
Common Mistakes
1. Using Text Blocks for Single-Line Strings
Wrong
String name = """
Java
""";
Better
String name = "Java";
Use Text Blocks only when they improve readability.
2. Incorrect Closing Delimiter
Wrong
String text = """
Hello
""; // Missing one double quote
Correct
String text = """
Hello
""";
3. Ignoring Indentation
Poor indentation can make the output difficult to understand.
Always format Text Blocks consistently.
4. Assuming They Are a New Data Type
Text Blocks are not a new data type. They are simply another way of creating a String.
When Should You Use Text Blocks?
Use Text Blocks when working with:
- HTML pages
- Email templates
- SQL statements
- JSON responses
- XML files
- GraphQL queries
- Documentation
- Multi-line messages
- Configuration data
Avoid them for simple one-line strings where regular string literals are more concise.
Conclusion
Java Text Blocks are a modern language feature that significantly improves the way developers work with multi-line strings. By eliminating unnecessary string concatenation, reducing escape sequences, and preserving formatting, they make source code cleaner, more readable, and easier to maintain.
Whether you’re embedding HTML templates, JSON payloads, SQL queries, XML documents, or email templates, Text Blocks provide a much more elegant solution than traditional string literals.