Java 15 Text Blocks

Java 15 Text Blocks

String literals on Steroids

Video Reference: youtube.com/watch?v=bDtVUndO2j8&ab_chan.. The code: github.com/Java-Complete-Tutorial/text-bloc..

Text blocks have officially been out in Java for a while now. They came out in Java 15, but at the time of writing this article we are at Java 17. I have yet to see them used in the wild, but I have used them myself for a few projects so I want to teach you how to use them to make your experience working with Strings more pleasant.

Concrete Improvements by Using Text Blocks

The best way to illustrate the usefulness of Text Blocks is to show you how you would do certain things in Java using regular String literals -- and then how to do the same thing with Text Block literals.

Standard Multi-line Strings

Here is one way you may choose to represent multiple lines of text. The \n character is a newline character.

String paragraph = "I am a paragraph of text.\n" +
                   "I am a paragraph of text.\n" +
                   "I am a paragraph of text.\n" +
                   "I am a paragraph of text.\n";

With text blocks:

paragraph = """
            I am a paragraph of text.
            I am a paragraph of text.
            I am a paragraph of text.
            I am a paragraph of text.
            """;

JSON Text

JSON text in Java has always been particularly painful to represent in Strings. Now, you don't need to deal with that pain.

String json = "{\"name\":\"Kody\",\"age\":\"24\"}";

With text blocks:

json = """
            {
                "name": "Kody",
                "age": "24"
            }
            """;

HTML

The improvement here is obvious.

String html = "<html>\n" +
                      "    <head>\n" +
                      "        <title>My Title</title>\n" +
                      "    </head>\n" +
                      "    <body>\n" +
                      "        <h1>My Heading</h1>\n" +
                      "        <p>My Paragraph</p>\n" +
                      "    </body>\n" +
                      "</html>";

Using text blocks:

html = """
            <html>
                <head>
                    <title>My Title</title>
                </head>
                <body>
                    <h1>My Heading</h1>
                    <p>My Paragraph</p>
                </body>
            </html>
                """;

Doesn't that just look like HTML? And make you feel good about yourself?

More Stuff

You get the idea, you can use text blocks to represent any kind of String data you want. What I want to do now is show you some more intricacies of text blocks.

Ending newline

If you try printing any of the Strings above, you will see that the text block puts a newline character at the end of the last line.

If you don't want a newline to be added at the very end of the String, put the closing triple quotes(""") on the same line as the last line of the String.

Try this code:

paragraph = """
                I am a paragraph of text.
                I am a paragraph of text.
                I am a paragraph of text.
                I am a paragraph of text.
                """;
        System.out.println(paragraph);

paragraph = """
                I am a paragraph of text.
                I am a paragraph of text.
                I am a paragraph of text.
                I am a paragraph of text.""";
        System.out.println(paragraph);

Indentation and Whitespace

Another thing is indentation for text blocks.

By default, Java is smart enough to know how to indent your Strings based off of the position of the lines of text.

To override this, you can use the closing quotes and position it where you want the indentation to begin.

image.png

I used an image here because you can see that IntelliJ IDEA(and probably other IDE's) will put a line to indicate where the line starts.

Escape Sequences

Remember having to escape characters in Strings? Yeah, not anymore! The reason you needed to escape quotes in String literals is because Java won't be able to differentiate between the quotes that are a part of the String and the quotes that start and close the literal. Since text blocks are denoted by triple double-quotes, you can use single double-quotes without escaping.

String text = "I am a \"string\" with a \n newline and a tab.";
text = """
            I am a "string" with a
            newline and a tab   .
            """;

You do need to escape triple quotes, though. But when are you ever going to be using triple quotes anyway? And whitespace on the end of a line is removed by the Text Block, so you have to escape it if you want it to remain.

text = """
            I am a \"""string\""" with a
            newline and a tab   .
            and some extra whitespace:                 \s
            .""";

String formatting

One of the common ways to output a String is to use the printf() method, and it automatically replaces parts of the String with the values you pass in.

System.out.printf("""
            I am a %s with a
            newline and a tab   .
            and some extra whitespace:                 \s
            .""", "string");

The example above shows that you can use text blocks in any place you would use a normal String literal, which makes sense because a text block equates to a String.

In JDK 15, they added the String.formatted() method so you can do the same thing you did above, but upon Strings or String literals directly if you want to.

System.out.println("""
            \nHey, my name is %s and I am %d years old.""".formatted("John", 25));

Closing Comments

As you can see, text blocks are very simple to use but offer some sexy improvements over traditional String literals that we use every day in Java. The most powerful feature of them in my mind is the fact that you can represent a String in Java code exactly how you would want it to be represented internally or when outputted. It makes them much more readable and easier to work with.

I hope this was informative and detailed enough to help you understand how you can begin using them yourself. If you have anything to add or feedback, drop a comment below.