Java 13: Text Blocks
Java 13 has delivered the long-awaited multiline strings or Text Blocks. You no longer need to concatenate strings that span multiple lines or escape special characters, which really improves the readability of your code. Text blocks are a preview language feature, which means that they must be explicitly enabled in the Java compiler and runtime using the --enable-preview
flag.
Here is an example of a text block:
1 2 3 4 5 6 | String textBlock = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" "; |
As shown above, a text block is enclosed by three double quotes ("""
). The opening """
cannot be followed by any non-whitespace characters i.e. the actual text must start on the line following the opening delimiter. You do not need to escape any special characters within the text block, which is great!
In previous versions of Java, you would have had to write it like this:
1 2 3 4 5 | final String old = "<html>\n" + "\t<body>\n" + "\t\t<p style=\"color:red\">This is a text block</p>\n" + "\t</body>\n" + "</html>" ; |
In fact, in this example, textBlock == old
because both have exactly the same content and refer to the same object in the String
pool.
Now let’s take a look at how leading whitespace is handled by considering the following two text blocks:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | String textBlock1 = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" "; String textBlock2 = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" "; |
If you print out these two text blocks, the first one is printed out as:
1 2 3 4 5 | <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> |
and the second one as:
1 2 3 4 5 | <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> |
The leftmost non-whitespace character on any of the lines in the text block or the leftmost closing delimiter determines the “starting point” of the whole block and whitespace is preserved on each line from this starting point.
Another point to note is that trailing whitespace at the end of each line is removed in text blocks but you can use the octal escape sequence \040
to preserve it as shown below:
1 2 3 | String octal = "" " line 1 \ 040 line 2 "" "; |
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 13: Text Blocks Opinions expressed by Java Code Geeks contributors are their own. |