Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 24, 2021 04:32 pm GMT

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>
" + " <body>
" + " <p>Hello, world</p>
" + " </body>
" + "</html>
";

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>""";

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\"
" + "WHERE \"CITY\" = 'CURITIBA'
" + "ORDER BY \"EMP_ID\", \"LAST_NAME\";
";

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";          """;

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!


Original Link: https://dev.to/andremoriya/jep-378-text-blocks-new-way-to-use-string-in-java-3f7g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To