Java Text Blocks

The text blocks is Java's way to simplify rendering of a string that spans multiple lines. A text block begins with three double-quote characters followed by a line terminator.^1


String text = """
    The quick 
    brown fox 
    jumps over 
    the lazy dog""";

The above example is equivalent to:

String text = "The quick \n"
    + "brown fox \n" 
    + "jumps over \n"
    + "the lazy dog";

Notice who how simple the example against its equivalent.

Incidental and essential white space

The java text blocks differentiates the incidental white space from essential white space^1. Like the following example:

void writeHTML() {
    String html = """
········    <body>
········        <p>Hello World.</p>
········    </body>

The dots, preceding the tag represents the incidental white spaces while the space preceding the tag not including the dots, represents the essential white spaces.

Normally the left incidental white space can be controlled by the location of the ending delimiter of the text blocks.

Trailing white space on each line in a text block is also considered incidental and is stripped away by the Java compiler^1.

Removing the ending new line of each line

Using the backslash at the end of each line will remove the implicit \n character.

String text = """
    The quick \
    brown fox \
    jumps over \
    the lazy dog""";

If you output the preceding variable it will become a single line like the following:

The quick brown fox jumps over the lazy dog