How to use text blocks in Java 15

Will
2 min readSep 17, 2020

This article tells everything you need to know about text blocks in code examples.

Where can I find it?

Download and install JDK 15 from here. Verify in command line.

How to write it in code?

String example = """
example string""";

A line terminator after the opening quotes are needed. So this won’t work:

// error: illegal text block open delimiter sequence, missing line terminator
String example = """example string""";

What are the beneficial use cases?

There are many use cases where we can get benefit from using text blocks but I only list 3 typical ones.

HTML

Before

@Language("HTML")
String htmlOldWay = "<!DOCTYPE html>\n" +
"<html>\n" +
" " +
"<body>\n" +
" " +
"<h2>HTML Buttons</h2>\n" +
" " +
"<p>HTML buttons are defined with the button tag:</p>\n" +
" " +
"<button>Click me</button>\n" +
" " +
"</body>\n" +
"</html>\n";

After

@Language("HTML")
String htmlInTextBlock = """
<!DOCTYPE html>
<html>
<body>
<h2>HTML Buttons</h2>
<p>HTML buttons are defined with the button tag:</p>
<button>Click me</button>
</body>
</html>
""";

Note that text block keeps indents as well.

JSON

Before

@Language("Json")
String jsonOldWay = "{\n" +
" \"name\": \"John\",\n" +
" \"age\": 30,\n" +
" \"car\": null\n" +
"}\n";

After

@Language("Json")
String jsonInTextBlock = """
{
"name": "John",
"age": 30,
"car": null
}
""";

SQL

Before

@Language("Oracle")
String sqlOldWay = "SELECT column_name(S)\n" +
"FROM TABLE1\n" +
" " +
"INNER JOIN TABLE2\n" +
" " +
"ON TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME;";

After

@Language("Oracle")
String sqlInTextBlock = """
SELECT column_name(S)
FROM TABLE1
INNER JOIN TABLE2
ON TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME;
""";

How to escape special characters?

No need to escape newlines and double quotes in text block.

String text = """
This is text with line break
and "double quotes"
""";
assertThat(text).isEqualTo("This is text with line break\n and \"double quotes\"\n");

And you can still escape special characters in normal way.

String text2 = """
This is text with line break\n\t and slashes /\\""";
assertThat(text2).isEqualTo("This is text with line break\n\t and slashes /\\");

Anything else?

A new method formatted is added to enable easier parameter inserting with text block.

String text3 = """
This is a parameter %s""";
assertThat(text3.formatted("param1")).isEqualTo("This is a parameter param1");

Enjoy!

PS: You can find all the code samples here.

--

--