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 contentString::translateEscapes()
: used to translate escape sequencesString::formatted(Object... args)
: simplify value substitution in the text block
That’s a sneak peek at text blocks. Hope you enjoy it
2 thoughts on “Java 13 – Text Blocks”