Java Text Blocks Introduction

A complete guide to Java Text Blocks feature. Learn to write multi-line string literals with Java Text Blocks while keeping them well formatted and readable without worrying about escaping characters.

Overview

The Java Text Blocks is a new feature of String literal. We can use Text Blocks to write multi-line strings in our programs, without bothering about any escape sequences or concatenations.

In this article we will begin by understanding the basics of text blocks, their syntax, and need. Next, we will understand how the smart indentation helps to preserve the literals formatted. We will also see how can we escape or keep the new line characters and also to escape various special characters like tabs and spaces.

Java Text Blocks Availability

Many developers missed this feature in Java for a long time. Finally, Java introduced this feature as a preview in Java 13, and Java 14. Finally, Java made text blocks a standard feature in Java SE 15 release.

If you are using Java versions 13, or 14 you will have to enable preview feature to be able to try Java Text Blocks.

What is Java Text Block

A text box is a new type of literal in Java, and it can be used to represent any type of string. It reduces any accidental errors, or complexities in writing multi-line string literals, as well as it improves the expressiveness and readability.

In Java code, we often write multi-line strings. Most of the times multi-line string literals are required to represent SQL, HTML, XML, and JSON etc. in Java. However, without text blocks the we need to surround each line into double quotes ("") and append all of them together. Or, we need to put new line characters where we expect a new line. There are many ways in which it can go wrong. Also, it reduces the readability of the enclosed HTML, or SQL etc code.

Consider we have a SQL query like this, which has been indented correctly.

SELECT s.id, s.fname as first_name, s.lname as last_name, s.year
FROM STUDENT s
WHERE s.year >= 2020
  AND s.fname like 'Jon%'Code language: SQL (Structured Query Language) (sql)

We want to add this query as a String literal using double quotes.

String query1 = "" +
    "SELECT s.id, s.fname as first_name, s.lname as last_name, s.year " +
    "FROM STUDENT s " +
    "WHERE s.year >= 2020 " +
    "AND s.fname like 'Jon%'" +
    "";Code language: Java (java)

With this, it is quite a job to append the double quotes on each line and concatenate the String. Also, when you miss the space character added at the end of each String, you will produce an invalid SQL query.

In order to avoid such formatting and correctness issues, text blocks are developed. Text blocks are represented in a pair of three double quotes (""").

Lets add the same query as String literal using text blocks (three double quotes).

String query2 = """
        SELECT s.id, s.fname as first_name, s.lname as last_name, s.year
        FROM STUDENT s
        WHERE s.year >= 2020
            AND s.fname like 'Jon%'
        """;Code language: Java (java)

The example shows, we have produced a String literal just like any other String. However, the literal in above example is more readable. Also, it preserves the original indentation automatically.

When we print both of these strings on new lines we get.

query1 :
SELECT s.id, s.fname as first_name, s.lname as last_name, s.year FROM STUDENT s WHERE s.year >= 2020 AND s.fname like 'Jon%'

query2 :
SELECT s.id, s.fname as first_name, s.lname as last_name, s.year
FROM STUDENT s
WHERE s.year >= 2020
    AND s.fname like 'Jon%'Code language: plaintext (plaintext)

We can see, with the text blocks the indentations are preserved. However, it is interesting to see, the smart indentations in text blocks cleverly ignored the source code indentations. Next, we will learn how the smart indentations work with text blocks.

Text Block Indentations

Text blocks categorises the indentations into incidental or essential indentations.

The Incidentals indentations are added based on the source file indentation strategy and it is part of of the Java indentation practices. These indentations vary based on the IDE settings, developer preferences or any followed practices.

On the other hand, essential indentations are part of the String literal itself. For example, in the above SQL the AND clause is indented by from rest of the SQL lines.

The text blocks identifies these indentations, ignore the incidental indentations, and preserve the essential ones.

To do that, the text block calculates total number of white spaces appear on the left of each line. Next, it picks up the line having least indentation of all and marks that indentation as incidental indentation.

class StudentProvider {
    public String getStudentAsJson() {
        return """
                {
                    "id":1235,
                    "first_name":"Jon",
                    "last_name":"Snow",
                    "year":2025
                }
                """;
    }
}Code language: Java (java)

For example, in the above code the open curly brace character has 16 whitespaces before it, similar to the close curly brace character. And, both of them have the least indentation amongst the rest of the literal lines. Hence, the text block assumes these 16 white spaces as incidental indentation.

Each of the JSON fields have 20 whitespaces before them. Subtracting the 16 incidental spaces the remaining 4 whitespaces are considered as essential ones.

The text blocks simply ignore the 16 incidental spaces and keep all the essential ones. Let’s print the string from the above example.

{
    "id":1235,
    "first_name":"Jon",
    "last_name":"Snow",
    "year":2025
}Code language: JSON / JSON with Comments (json)

The output shows, that all the incidental spaces are ignored and the first opening brace appears at the extreme left.

Before we move to the next section, note that Text Blocks always ignore trailing white spaces that is the spaces appear on the right side of the String.

Text Block and New Lines

From the above two examples, it is clear that a text block always append line terminator at the end of each line. Which is why, our multi-line Strings are printed in multi-line form.

System Specific New Line Character

Different operating systems have a different line termination characters. However, text block always uses \n as its line separator. Also, we can use replace method to replace the default line separator with the one specific to the operating system.

Next example demonstrates replacing text block default line separators by system line separators.

String multiLine = """
        This
        is 
        an
        Example
        """;
multiLine = multiLine.replaceAll("\n", System.lineSeparator());Code language: Java (java)

Escape the Line Terminators

Sometimes we have a single line string literal which is very long. Thus, in order to keep it readable, we want to keep it in multi-line form in source file by using text blocks. However, we do not want the single line string to be divided into multiple lines.

To do so we can use the escape character / to escape the line terminators also called as new line characters.

Remember, escaping new line character will print the string literal in single line.

String multiLine = """
        This \
        is \
        an \
        Example \
        """;

System.out.println(multiLine);Code language: Java (java)

The output it prints is

This is an Example 
Code language: plaintext (plaintext)

In the above code, we have correctly escaped all new line characters.

Escaping Characters in Text Blocks

We have already covered How to escape line terminators or new line characters in text blocks.

Text blocks support all escape sequences that a normal String literals support to. Which includes \n, \t, \’, \”, and \\. However, we do not need to escape any of these characters in Text Blocks, as text blocks escape them by default.

However, the """ marks the start and end of the a block. Thus, we need to escape it if it appears inside text block. To do so, we can use the generic escape character \ inside a text block.

String multiLine = """
        I have (\""") in me
        """;Code language: Java (java)

Output:

I have (""") in meCode language: plaintext (plaintext)

Similarly, we can also add tabs by using \t.

String multiLine = """
        I have '\t' in me
        """;Code language: Java (java)

Output:

I have '	' in meCode language: plaintext (plaintext)

Text Blocks and Trailing Spaces

Trailing spaces are the spaces that appear after each line. As stated above Text Blocks ignore any trailing spaces that appear on each line. However, if we want to keep them, we can do so by adding \s character in the end.

String multiLine = """
        Line 1          
        Line 2          \s
        Line 3                  
        """;

System.out.println(multiLine.replaceAll(" ", "."));Code language: Java (java)

There are tailing spaces in above literal, however they are not visible.

There are 10 white spaces at the end of each line. Out of which, only in the second line the 10 spaces are followed by a \s character.

When we print the string by replacing all each space character by a dot we get.

Line.1
Line.2...........
Line.3Code language: plaintext (plaintext)

From the output it is clear that, Text block has replaced all the trailing white spaces except for line to which has \s character in the end.

Summary

In this article we had a detailed overview of Java Text Blocks feature. We learned that text blocks are more readable, and convenient way of writing multi-line string literals in java code. Also, the text blocks smartly preserves essential white spaces while ignoring the incidental ones. Next, we also saw various ways of escaping characters in text blocks including new line character and white space characters.
While doing so, we have also written plenty of handy examples to try the concepts on our own. For more on Java, please visit Introduction to Java.