We are all familiar with simple Strings such as “Hello World”. How do we define Strings that span multiple lines? An easy way to do this is using text blocks.
What are text blocks?
We can use text blocks to define multiline String literals in a readable way, thus avoiding concatenation operators and escape sequences.
For example, consider the following String that contains an HTML code snippet like this.
String html = """
<HTML>
<BODY>
<H1>"Java 17 Certification"</H1>
</BODY>
</HTML>""";
If we had to define such a String earlier, we had to do it as below. As we can see, this code is not readable or easy to understand.
String html1 =
"<HTML>\n\t<BODY>\n\t\t<H1>\"Java 17 Certification""</H1> \n\t</BODY>\n</HTML>\n";
What is the syntax for text blocks?
A text block begins with three double-quote characters followed by a line terminator.
Here is an example.
String name = """
one
two
three
""";
System.out.println(name);
The output will be
one
two
three