Text Blocks in Java 13
Text Blocks is one of the new features introduced in Java 13. Assigning a long string value to an Object has been a headache in Java. Thanks to text blocks, that’s not the case anymore.
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 format when desired. This is advertised as a preview feature in Java 13 but it’s fully functional as per our testing.
A text block consists of zero or more content characters, enclosed by opening and closing delimiters. It can be also called as Two Dimensional block of text.
String html = """ <html> <body> <p>Text Blocks feature test</p> </body> </html> """;
String story = """ "WI'm a little teapot Short and stout Here is my handle (one hand on hip) Here is my spout (other arm out straight) When I get all steamed up Hear me shout "Tip me over and pour me out!"" """;
The opening delimiter is a sequence of three double quote characters (
""") followed by zero or more white spaces followed by a line terminator. The content begins at the first character after the line terminator of the opening delimiter.
The closing delimiter is a sequence of three double quote characters. The content ends at the last character before the first double quote of the closing delimiter.
Compile time processing
A text block is a String constant, 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:
- Line terminators in the content are translated to LF (\u000A). The purpose of this translation is to follow the principle of least surprise when moving Java source code across platforms.
- Incidental white space surrounding the content, introduced to match the indentation of Java source code, is removed.
- Escape sequences in the content are interpreted. Performing interpretation as the final step means developers can write escape sequences such as \n without them being modified or deleted by earlier steps.
Leave a Reply