Text Blocks in Java – JEP 378 – Since Java 15

Another interesting feature that was added to Java is the text blocks. It was a preview feature in Java 13 , 14 and became final and permanent in Java 15.

What are text blocks ?

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.

Example:

Assign a JSON to a string as a text block.

String jsonTextBlock = """
{
name:"John",
age:31,
city:"New York"
}
""";

Prior to text block you would write the same as shown below.

String jsonString = "{\n" +
" name:\"John\",\n" +
" age:31,\n" +
" city:\"New York\"\n" +
"}";

How cleaner it is if we use the text block ? . You don’t need to escape the quotes or add new line characters in text blocks.

Syntax:

A text block begins with three double-quote characters followed by a line terminator. You can’t put a text block on a single line, nor can the contents of the text block follow the three opening double-quotes without an intervening line terminator. The reason for this is that text blocks are primarily designed to support multi-line strings, and requiring the initial line terminator simplifies the indentation handling rules.

//Error : illegal text block open delimiter sequence, missing line terminator
String name = """My name is """;

//Error
String name1 = """ My
               name is """;

//OK
String name2 = """
        My name is """;

//OK
String name3 = """
        My name is 
        """;

SQL in Java Example:

Using text block to write an sql query in Java the cleaner way. Here we are using the new instance method String::formatted to pass in the sql parameters.

String customer_id = "12345";
String city = "New York";

String sql = """
              Select * from customer c, address a where
              c.cid = a.cid and
              c.cid = %s
              a.city= '%s'
              """.formatted(customer_id, city);

System.out.println(sql);


//OUTPUT: 
Select * from customer c, address a where
c.cid = a.cid and
c.cid = 12345
a.city= 'New York'
%d bloggers like this: