Saturday, October 26, 2019

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:

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:

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:

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:

<html>
  <body>
    <p style="color:red">This is a text block</p>
  </body>
</html>

and the second one as:

        <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:

String octal = """
    line 1    \040
 line 2""";

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.