Java 13 introduced Text Blocks as a preview feature. It got enhanced and continued as a preview feature in Java 14 release. Java 15 has made this a permanent feature of the language.
So what is a text block?
Short answer is it is a multi-line string with special syntax. The purpose of introducing it is to simplify and minimize the code required to create a multi-line strings.
Assume for example, we want to capture this famous last stanza of Robert Frost's poem as a Java String.
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
Below code snippet captures this
String poemString = "The woods are lovely, dark and deep,\n"
+ "But I have promises to keep,\n"
+ "And miles to go before I sleep,\n"
+ "And miles to go before I sleep.";
But this has multiple strings appended through + operator. Also note the '\n' included at the end of each line to capture the new line into the String.
Things would get more complicated for lengthy string literals, which is not uncommon with HTMLs, XMLs & JSONs often getting embedded in code. And not to forget the performance implication of many String appends leading to usage of StringBuilder and StringBuffer for optimization.
Wouldn't it be better if we can get rid of this and have a simpler syntax to capture such multi-line strings?
This essentially is what the Text Block feature provides.
Below snippet shows how to use a Text Block to capture the same String
String poemTextBlock = """
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
""";
We start and end a Text Block with three double quotes as in """. Format of the text inside of the Text Block is preserved and there is no need to add additional '\n' for the new lines.
This will greatly simplify the code when embedding HTML, XML, JSON, SQL, JavaScript or other such code snippet in a string literal.
The full code is embedded below
public class Main {
public static void main(String[] args) {
String poemTextBlock = """
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
""";
String poemString = "The woods are lovely, dark and deep,\n"
+ "But I have promises to keep,\n"
+ "And miles to go before I sleep,\n"
+ "And miles to go before I sleep.";
System.out.println("Text Block: "+poemTextBlock);
System.out.println("String: "+poemString);
}
}
Note that there is a minor difference in the values represented by poemString & poemTextBlock in the above code.
Try to figure out that difference... We will uncover that in our next post.
Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Text-blocks/The-Text-Blocks
No comments:
Post a Comment