📘 Introduction
Dealing with multiline strings in Java has always been a bit cumbersome—developers had to concatenate strings using +
, escape line breaks, or use external files. This made code messy, harder to read, and prone to errors.
Java 13 introduced Text Blocks as a preview feature, which became a permanent feature in Java 15. Text blocks provide a clean, concise, and readable way to declare multiline strings without boilerplate. They significantly improve readability and reduce the chances of bugs in string-heavy code.
In this tutorial, we’ll explore how to use text blocks effectively with real-world examples, version notes, and best practices.
🔍 What is a Text Block?
A text block is a multiline string literal that begins and ends with triple double-quote ("""
) and preserves the content between them, including new lines and indentation.
✅ Syntax
String json = """
{
"name": "Java",
"version": 21
}
""";
No need for escape characters or +
operators!
🧠 Purpose and Benefits
- ✅ Clean multiline string support
- ✅ No need for escaping double quotes or line breaks
- ✅ Preserves structure and formatting (great for HTML, JSON, SQL)
- ✅ Easy to edit and visualize
🔧 Example Use Cases
- Embedding JSON/XML in code
- Writing SQL queries inside DAOs
- Constructing HTML templates for emails
- Creating Markdown or documentation templates
📦 Example – SQL Query
String query = """
SELECT *
FROM users
WHERE status = 'ACTIVE'
ORDER BY created_at DESC;
""";
📦 Example – HTML Template
String html = """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""";
⚙️ Behavior and Formatting Rules
- Leading whitespace is trimmed based on the least-indented line
\
at the end of a line escapes the newline (useful for line continuation)- You can embed
"
without escaping
String quote = """
He said, "Text blocks are awesome!"
""";
📊 Java Version Support
Java Version | Text Blocks Support |
---|---|
Java 13 | Preview feature (must enable with --enable-preview ) |
Java 14 | Preview feature |
Java 15+ | Officially available and stable |
🚀 Refactoring Example
Before (pre-Java 13):
String sql = "SELECT * FROM users\n" +
"WHERE status = 'ACTIVE'\n" +
"ORDER BY created_at DESC;";
After (Java 15+):
String sql = """
SELECT * FROM users
WHERE status = 'ACTIVE'
ORDER BY created_at DESC;
""";
⚖️ Pros and Cons
✅ Pros
- Great readability and maintainability
- Native support for HTML/JSON/SQL formats
- No need for
\n
or escaping quotes
❌ Cons
- Available only from Java 13+ (standard from 15)
- Slight learning curve around indentation handling
📌 What's New in Java Versions?
- ✅ Java 13: Introduced text blocks as preview feature
- ✅ Java 14: Refined indentation and escaping
- ✅ Java 15: Text blocks became permanent
- ✅ Java 21: Works seamlessly with String templates (preview)
🧨 Edge Cases and Gotchas
- Watch out for inconsistent indentation — Java uses the least-indented line to determine baseline
- Trailing whitespaces are preserved
- You can escape a newline using
\
if needed for line continuation
String code = """
public void hello() { \
System.out.println("Hello");
}
""";
🧹 Best Practices
- Use for any long-form string with structure (SQL, HTML, JSON, Markdown)
- Avoid mixing tabs and spaces
- Use consistent indentation
- Don’t use for short single-line strings unless you're planning to expand
📋 Conclusion and Key Takeaways
Text blocks are a powerful and long-overdue addition to the Java language. They significantly improve the readability and maintainability of code that deals with multiline strings, especially in templating-heavy domains like web development or database operations.
By upgrading to Java 15+, you can take full advantage of this cleaner syntax and write more expressive code.
❓ FAQ: Frequently Asked Questions
-
Are text blocks available in Java 8 or 11?
No, text blocks were introduced as a preview in Java 13 and made stable in Java 15. -
Do I need to escape double quotes inside text blocks?
No, you can use"
directly inside a text block without escaping. -
How do line breaks work in text blocks?
They are preserved automatically. You can use\
to escape a line break. -
What’s the difference between
\n
and real newlines in text blocks?
Text blocks preserve actual newlines;\n
is just a character sequence. -
Is it okay to indent text blocks inside methods or classes?
Yes, Java adjusts based on the least-indented line within the block. -
Can I use text blocks in annotations or constants?
Yes, but the Java version must be 15 or above. -
Can I use text blocks with formatted strings?
Yes, useString.format()
or Java 21’s string templates for that. -
Can I disable trailing whitespace trimming?
No, but you can control whitespace by managing your block content and indentation carefully. -
Do IDEs support text blocks well?
Most modern IDEs (IntelliJ, Eclipse, VS Code) support them fully from Java 15 onward. -
Will text blocks increase memory usage?
No, they’re compiled just like regular string literals.