Text Blocks
Constructing string literals that span multiple lines can be tedious using string concatenation and line terminators. Text blocks provide a better solution—avoiding having to escape tab, newline, and double-quote characters in the text, and in addition preserving indentation of a multiline string.
Basic Text Blocks
The string sql1 below represents a three-line SQL query. It is constructed using a text block, resulting in an object of type String. We will use it as an example to illustrate constructing text blocks.
String sql1 = “””
SELECT *
FROM Programmers
WHERE Language = ‘Java’;
“””;
The string literal resulting from entering the text block in the jshell tool:
sql1 ==> “SELECT *\nFROM Programmers\nWHERE Language = ‘Java’;\n”;
Printing the text block sql1 above will give the following result, where the underscore (_) is used as a visual marker to indicate the position after printing the resulting string:
SELECT *
FROM Programmers
WHERE Language = ‘Java’;
_
A text block starts with three double quotes (“””) and ends with three double quotes (“””). The opening delimiter of a text block consists of the opening three double quotes (followed by any spaces, tabs, or form feed characters) that must be terminated by a line terminator. The closing delimiter of a text block consists of three double quotes.
The content of a text block begins with the sequence of characters that immediately begins after the line terminator of the opening delimiter and ends with the first double quote of the closing delimiter. Note that the line terminator of the opening delimiter is not part of the text block’s content.
The following attempt to construct a text block will result in a compile-time error because of erroneous characters (i.e., the // comment) that follow the opening three double quotes of the text block.
String badBlock = “”” // (1) Compile-time error!
Not a good start.
“””;
The text block below results in an empty string (“”):
String emptyBlock = “””
“””;
Leave a Reply