Java 13: Text Block
Hi Folks,
In this post, I’ll explore a cool feature shipped with Java 13 release on the 17 September.
Most of the Java development embedding a snippet of different languages such as HTML, XML, SQL or JSON. If you had any experience in the above snippet use as a String literal, you may know how hard to editing with escapes and concatenation before compile successfully. In order to avoid the complexity of String literal formatting and concatenation, Java 13 introduced Text Block, a multi-line string literal that avoids the need for escape sequences, automatically formats and provides developers to control over format freedom with effective and efficient manner.
In OpenJDK documentation Text Block feature described as,
A text block is a new kind of literal in the Java language. It may be used to denote a string anywhere that a string literal could appear, but offers greater expressiveness and less accidental complexity.
Still, Text Block is a preview language feature in JDK 13, which means fully specified, fully implemented, and yet impermanent. If you need to get some experience you have to follow a different compilation option to use preview language features. I’ll explain later.
Demo
Note: When you compile a source code which has preview feature, you should pass “ — enable-preview — release 13” option in compile-time because preview features are disabled by default.And in run time “ — enable-preview” option should use before pass the main class.
Same as the String literal in Java, Text Block also enclosed by opening an closing delimiters. The opening delimiter is a sequence of three double characters (“ “ “). But you have to start your content with a new line otherwise, you end up with ‘illegal text block open delimiter sequence, missing line terminator’ compilation error.
Closing delimiters also should be the sequence of three double characters (“ “ “) same as the open delimiters but content may end as an inline or a new line of closing double-quotes. But base on your choice it will represent two deferent compilation outputs. Look at the following examples.
According to Java release documentation, A text block is a constant expression of type String, just like a string literal. However, unlike a string literal, the content of a text block is processed by the Java compiler in three distinct steps. But at run time, a text block is evaluated to an instance of String, just like a string literal. Instances of String that are derived from text blocks are indistinguishable form instances derived from string literals.
I hope you had an extensive idea about Text Block.
Happy Coding…