Java 13 – Text Blocks

Java 13 adds a preview feature that supports JEP 355 – Text Blocks (previously JEP 326 – Raw String Literals). The goal is simple: make it easier to write String that span over several lines. This is especially useful when we are representing a SQL statement or a JSON.

Today, if we want to write a SQL statement it would look something like that:

String sql = "SELECT FIRST_NAME, LAST_NAME, AGE \n " +
             "FROM EMPLOYEE \n" +
             "WHERE AGE > 50";

The same query using Text Blocks can be written as:

String sql = """
             SELECT FIRST_NAME, LAST_NAME, AGE
             FROM EMPLOYEE
             WHERE AGE > 50
             """;

Much more readable right? Also, there’s no need to escape characters as single or double-quotes

Note the correct syntax. Three quotation marks(“””) to start the Text Block, followed by a mandatory new line where the code starts. Another three quotes set the end of the block.

String song = """
              The itsy bitsy spider climbed up the waterspout.
              Down came the rain
              and washed the spider out.""";
//okay
String song = """The itsy bitsy spider climbed up the waterspout.
Down came the rain
and washed the spider out.""";
//Illegal text block start. Missing new line after opening quotes

Note the behavior of text blocks.

String cities = """
                Paris
                New York
                Sao Paulo
                """;
//Is equivalent to "Paris\nNew York\nSaoPaulo\n"

If a line terminator is not required, then the closing delimiter can be placed on the last line of the content.

String cities = """
                Paris
                New York
                Sao Paulo""";
//Is equivalent to "Paris\nNew York\nSaoPaulo"

The position of the closing delimiter is important.

System.out.println("""
                    Hello World!
                    """);
//>Hello World!

System.out.println("""
    Hello World!
""");
//>    Hello World!

To support text blocks, new methods will be added to the String class

  • String::stripIndent(): used to strip away incidental white space from the text block content
  • String::translateEscapes(): used to translate escape sequences
  • String::formatted(Object... args): simplify value substitution in the text block

That’s a sneak peek at text blocks. Hope you enjoy it

Advertisement

2 thoughts on “Java 13 – Text Blocks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.