DEV Community

André Moriya
André Moriya

Posted on

JEP 378: Text Blocks. New way to use String in Java

Introduction

In this article, I'm going to show the Java Text Block feature!

This feature is available since Java 15 and brings to us , a simple way to write Strings.

Now some examples.

Writing simple HTML

In this first example, when you need to write Html code. Before this feature, we need to do this:

var html = "<html>\n" +
              "    <body>\n" +
              "        <p>Hello, world</p>\n" +
              "    </body>\n" +
              "</html>\n";
Enter fullscreen mode Exit fullscreen mode

In this case, we had to concatenate each line to write this simple code.
But see now with this new feature:

var html = """
    <html>
        <body>
            <p>Hello, world</p>
        </body>
    </html>
""";
Enter fullscreen mode Exit fullscreen mode

In these two cases, the output is:

html

Writing SQL queries

In this second case, when you need to create a query for your application.

Your code will look something like this:

var query = "SELECT \"ID\", \"FIRST_NAME\", \"LAST_NAME\" FROM \"PERSON\"\n" + 
                   "WHERE \"CITY\" = 'CURITIBA'\n" + 
                   "ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";

Enter fullscreen mode Exit fullscreen mode

With Text Blocks, this code above will look like this:

var query = """
          SELECT "EMP_ID",  "FIRST_NAME", "LAST_NAME" FROM "PERSON_TB"
          WHERE "CITY" = 'CURITIBA'
          ORDER BY "EMP_ID", "LAST_NAME";
          """;
Enter fullscreen mode Exit fullscreen mode

And these two cases, the output is:

query

Conclusion

We saw the difference between writing Strings in Java with and without Text Blocks. Before it is more difficult and easier to make mistakes.

This feature brings an easy way to write a test, for example, when you need to test a Rest API passing a JSON. Or when you need to write a complex query.

If you want to know more about it, access this link.

And If you have any questions, leave a comment or ask me on my twitter.

A special thanks to Yugo Sakamoto for helping me in this post!

Thanks very much!

Top comments (2)

Collapse
 
dearrudam profile image
Maximillian Arruda

Direct to the point!!! Great article!!!! Congrats!!!

Collapse
 
andremoriya profile image
André Moriya

Tks Max for your feedback