Text blocks have been introduced in Java since version 13 as a preview, after which they were added on a permanent basis in version 15. Text blocks provide an opportunity to create a multi-line string literal in a more convenient way, without using concatenations and escape sequences. It also improves the readability and support of the code in the future.

It is especially convenient to use the java text block when embedding XML, HTML, JSON, and SQL query fragments in the code.

An example of writing a JSON string the old-fashioned way:

String customerOld = "{\n" +
" \"firstName\": \"Gabriella",\n" +
" \"lastName\": \"Hart",\n" +
" \"age\": 35\n" +
"}";

The same with the use of a text block:

String customerNew = """
{
"firstName": "Gabriella"
"lastName": "Hart"
"age": 35
}
""";
  • the text block is created using triple quotes “””. It is also important to note that in the first line after opening the block, there should be no more characters after “””, otherwise an error will occur;
  • now there is no need to concatenate strings with + and use the escape sequence \n to break a string;
  • no need to escape double quotes.

Formatting in a java text block

The result of a text block is a Java String that supports all its methods (trim, substring, replace, etc.). Using the formatted method, we can conveniently format our text:

String customerNew = """
{
"firstName": "%s",
"lastName": "%s",
"age": %d
}
""".formatted("Gabriella", "Hart", 35).