Text Blocks – Selected API Classes

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.

Click here to view code image

String sql1 = “””
SELECT *
FROM Programmers
WHERE Language = ‘Java’;
“””;

The string literal resulting from entering the text block in the jshell tool:

Click here to view code image

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:

Click here to view code image

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.

Click here to view code image

String badBlock = “””      // (1) Compile-time error!
Not a good start.
“””;

The text block below results in an empty string (“”):

Click here to view code image

String emptyBlock = “””
“””;


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *