java text blocksjava text blocks
HappyCoders Glasses

Java Text Blocks

Sven Woltmann
Sven Woltmann
Last update: January 11, 2024

In Java 15, text blocks (multiline strings) were introduced under Project Amber, whose goal is to develop and introduce new language features.

In this article, you will learn:

  • Why do we need text blocks?
  • How to notate text blocks in Java?
  • How to indent a text block?
  • Which escape sequences can or must we use in a text block?

Multiline Strings in Java

Before Java 15, when we wanted to define a multi-line string in Java, it usually looked like this:

String sql =
    "  SELECT id, firstName, lastName\n"
        + "    FROM Employee\n"
        + "   WHERE departmentId = \"IT\"\n"
        + "ORDER BY lastName, firstName";

String html =
    "<html>\n"
        + "  <body>\n"
        + "    <p>Hello World!</p>\n"
        + "  </body>\n"
        + "</html>";Code language: Java (java)

We had to replace line breaks and quotes with escape sequences (\n and \"). And to split the string into several lines in a somewhat readable way, we had to divide it and concatenate it again with +. That was not too bad (because the compiler made a single string out of it again), but it was not pleasant either.

Text Block Notation

Starting with Java 15, we can notate multiline strings as "text blocks":

String sql = """
      SELECT id, firstName, lastName
        FROM Employee
       WHERE departmentId = "IT"
    ORDER BY lastName, firstName""";

String html = """
    <html>
      <body>
        <p>Hello World!</p>
      </body>
    </html>""";Code language: Java (java)

The text block starts and ends with three quotation marks each. The following rules apply:

  • The starting quotes must be followed by a line break (which does not become part of the string).
  • If there is a line break before the ending quotes, this line break will be part of the string.
  • You do not need to escape single or double quotes within the text block, but you may (though SCA tools such as SonarLint recommend not doing so).
  • If you want to write more than two quotation marks, you have to escape every third of them.

One of the first questions developers ask themselves is:

How Far Must the Text Block Be Indented?

The answer is: it doesn't matter.

The text block starts at the character furthest to the left (in the first example above, at the "O" of "ORDER BY"; and in the second example, at the angle brackets in the first and last line).

The following three notations all lead to the same result:

    String sql1 = """
          SELECT id, firstName, lastName
            FROM Employee
           WHERE departmentId = "IT"
        ORDER BY lastName, firstName""";

    String sql2 = """
                   SELECT id, firstName, lastName
                     FROM Employee
                    WHERE departmentId = "IT"
                 ORDER BY lastName, firstName""";

    String sql3 = """
  SELECT id, firstName, lastName
    FROM Employee
   WHERE departmentId = "IT"
ORDER BY lastName, firstName""";Code language: Java (java)

All three strings have the following content – regardless of the indentation in the source code:

  SELECT id, firstName, lastName
    FROM Employee
   WHERE departmentId = "IT"
ORDER BY lastName, firstNameCode language: plaintext (plaintext)

Modern IDEs give us a hand here by showing the left margin of the text block (IntelliJ by a green line):

Representation of the left margin of Java text blocks in IntelliJ
Representation of the left margin of Java text blocks in IntelliJ

But what if you want to create a text block that is indented?

There is a trick for this: You insert a line break before the closing quotation marks and place the quotation marks where the text block should start, e.g., like this:

String sql = """
      SELECT id, firstName, lastName
        FROM Employee
       WHERE departmentId = "IT"
    ORDER BY lastName, firstName
  """;Code language: Java (java)

The text block is now indented by two characters.

However, it also has a line break at the end. We can remove this with an escape sequence. Escape sequences are discussed in the following chapter.

Escape Sequences in Text Blocks

Text blocks have the advantage that the escape sequences most commonly used in strings, namely \" for quotes and \n for a line break, are no longer needed.

Instead, there are two new escape sequences:

Escape Sequence: Backslash at the End of the Line

In the previous chapter, you saw that you can indent a text block by inserting a line break before the closing quotation marks. However, this line break is then also contained in the string. To remove it, you can put a backslash at the end of the last line:

String sql = """
      SELECT id, firstName, lastName
        FROM Employee
       WHERE departmentId = "IT"
    ORDER BY lastName, firstName\
  """;Code language: Java (java)

The backslash at the line end ensures that the string does not contain a line break at that position.

This feature is not limited to the last line – you can end any line with a backslash:

String sql = """
    SELECT id, firstName, lastName \
    FROM Employee
    WHERE departmentId = "IT" \
    ORDER BY lastName, firstName""";Code language: Java (java)

This string thus contains only a single line break after "Employee":

SELECT id, firstName, lastName FROM Employee
WHERE departmentId = "IT" ORDER BY lastName, firstNameCode language: plaintext (plaintext)

This feature is helpful if you want to split a one-line string, e.g., a very long log statement, over several lines in the source code.

Escape Sequence: \s

Another escape sequence you can use to format a text block is "\s".

Trailing spaces are removed from each line by default, as in the following example (the dots are supposed to represent the spaces):

String text = """
    one·····
    two·····
    three···""";

text.lines().map(line -> "|" + line + "|").forEachOrdered(System.out::println);Code language: Java (java)

The output of this code snippet is:

|one|
|two|
|three|Code language: plaintext (plaintext)

To preserve the spaces, you can replace them with the escape sequence "\s":

String text = """
    one\s\s\s\s\s
    two\s\s\s\s\s
    three\s\s\s""";Code language: Java (java)

It is clearer and completely sufficient if we only escape the last space:

String text = """
    one    \s
    two    \s
    three  \s""";Code language: Java (java)

Thus, the program prints the desired result:

|one     |
|two     |
|three   |Code language: plaintext (plaintext)

Now you have learned the complete range of functions of the text blocks. Have fun using them!

History of Text Blocks in Java

Text blocks were first introduced via JDK Enhancement Proposal (JEP) 355 as a preview feature in Java 13. They were a replacement for JEP 326, "Raw String Literals", which was not accepted by the community and subsequently withdrawn. If you're interested in the reasoning behind this, you can find it in this post by Brian Goetz on the jdk-dev mailing list.

In the second preview, JEP 368, the above-mentioned escape sequences were added in Java 14.

Due to positive feedback, text blocks were released as a production-ready feature in Java 15 by JDK Enhancement Proposal 378 without further changes.

Summary

Text blocks finally allow us to notate multi-line strings in Java code conveniently. They are enclosed in triple quotes. Quotation marks and line breaks no longer have to be replaced by confusing escape sequences.

If you liked the article, feel free to share it using one of the share buttons at the end. Do you already use text blocks? How do you like them? Leave a comment below!

If you want to be regularly informed about new articles on HappyCoders.eu, click here to sign up for the HappyCoders newsletter.