Text blocks were introduced in Java to make it easier to work with multi-line strings, especially when embedding longer chunks of text such as HTML, JSON, SQL, or XML in your code. A text block is a new way to represent strings that simplifies writing and formatting multi-line text, eliminating the need for excessive escape sequences and manual string concatenation.
Writing multi-line strings required lots of messy escape characters (\n
for new lines, \t
for tabs), making the code hard to read.
A text block is essentially a multi-line string that is wrapped in triple quotes ("""
). It preserves the original formatting, making the code cleaner and easier to read.
String textBlock = """
This is a text block.
It can span multiple lines.
You don't need to escape special characters like " or '.
""";
String sql = "SELECT * FROM accounts WHERE balance > 1000 " +
"AND account_type = 'SAVINGS' " +
"ORDER BY balance DESC;";
String sql = """
SELECT * FROM accounts WHERE balance > 1000 AND account_type = 'SAVINGS' ORDER BY balance DESC;
""";
String json = "{\n" +
" \"name\": \"Alice\",\n" +
" \"accountType\": \"SAVINGS\",\n" +
" \"balance\": 5000.75\n" +
"}";
String json = """
{
"name": "Alice",
"accountType": "SAVINGS",
"balance": 5000.75
}
""";
You can still use escape sequences within text blocks if needed. For example:
\n
for a new line (if you want to force one).\"
to escape double quotes inside a text block (though it's often not needed since text blocks handle most cases without escaping).String example = """
He said, "Hello!"
Welcome to the world of Java 17.
""";
Text blocks in Java 17 simplify working with multi-line strings, reducing boilerplate code and improving readability. They are particularly useful in projects where large blocks of text, such as SQL, JSON, HTML, or XML, need to be embedded into the code. The feature helps make the code cleaner and less error-prone.