4 Examples of Text Blocks in Java

While some programmers are troubled with frequent Java releases (it's actually hard to keep up), many are excited to see new features coming in Java every six months. I haven't been sharing a lot of new features lately, last I wrote about var from Java 10 and static factory from Java 9. Well, to be honest, I don't get much time to try out these new features and to publish articles on those, but a couple of new features from Java 12 and Java 13 caught my attention and I decided to give it a try and write something about them. So, the first feature in this series is the "Text block" of Java 13.

It's actually a pretty cool feature that takes the pain of escaping string literals in Java. You can use text blocks to write HTML and JSON just like you see them in the text pad. It also helps you to write multi-line strings without using any regular expression like \n.

If you know Groovy, it's like their multiline String feature, (If you don't groovy I suggest you learn it, it's a very useful tool, and if you need a resource check this course.) I have used that feature a couple of years ago and that's why it was a lot easier for me to pick up the text block of Java 13.

Well, it's not difficult at all, all you need to remember is that you need to declare the string literal using """ (three double quotes) instead of a single " (double quotes) which we use to declare String literals. The internal object is still String, which means you can use all kinds of string functions like length(), toUperCase(), toLowercase(), trim(), substring(), contains() etc with text block as well.

By the way, if you are new to Java and looking for a comprehensive course to learn Java in a guided and structured way, then you can also check out The Complete Java Masterclass course on Udemy. This 80-hour long course is the most comprehensive resource to learn Java online. 





4 Text Blocks Examples in Java for Beginners

Now that, you know what is text block of Java 13, let's see a couple of examples of declaring multi-line string, JSON, and HTML before and after Java 13 to understand how much difference text block makes in your code.


1. HTML using Text Block in Java 13

It's pretty common to write some piece of HTML in Java code, particularly if you are coding Servlet and JSPs or dealing with HTML files. Before Java 13 and Text Block you would write your HTML something like this:

String html = "<HTML>" +
"\n\t" + "<BODY>" +
"\n\t\t" + "<H1>\"HTML code in Java before Java 13!\"</H1>" +
"\n\t" + "</BODY>" +
"\n" + "</HTML>";

This is cluttered and messy and there is a chance that you miss a tag or an escape sequence, but not to worry, with Java 13 and Text block you can write the same code as below:

String html = """
<HTML>
<BODY>
<H1>"HTML code in Java using Text Block of Java 13"</H1>
</BODY>
</HTML>""";

This is much more clear, concise, and readable. All you needed to do is enclose the text using three double quotes (""") instead of one ("") in regular string.



2. JSON in Java 13 using Text Block

Another place where I think the Text block of Java 13 will make a big difference in code would be declaring JSON String. Sine JSON uses a lot of quotes and double quotes, you need to escape them and becuase of that, the actual JSON looks very messy when you have seen them in your Java text file or IDE.

For example, if you want to declare a JSON for testing in your Java file before Java 13, it would look something like below:

String json = "{\r\n" +
" \"author\":\"J. K. Rolling\",\r\n" +
" \"title\":\"Harry Potter and Half Blood Prince\",\r\n" +
" \"price\":20,\r\n" +
" \"characters\":[\"Harry\",\"Ron\",\"Hermione\"]\r\n" +
" }";

You can see it's again very clumsy, error-prone, and hard to read. On the other hand, the same JSON String with Java 13 Text block will look like below:

String json = """
{
"author":"J. K. Rolling",
"title":"Harry Potter and Half Blood Prince",
"price":20,
"characters":["Harry","Ron","Hermione"]
}""";

You can see the difference, it's much more readable now. There is no escape sequence, no backward slash, no \r\n, etc. 


3. Multiline String with Text Block

Now, let's see another example of the Java 13 Text block. You know many times you want to display a multiline string in Java, but you cannot do until you use a line breaker like "\n" inside your String. For example, if you want to display something like this

String output = "This is first line" +
"This is second line";

It looks like that both lines will be printed on separate lines but that's not the case. If you print them in console, you will see the following output:

This is the first lineThis is second line

If you want a multiline String, you need to use a "\n" between them like below:

String output = "This is the first line \n" +
"This is the second line";
System.out.println(output);

Now, it will print them on two lines as shown below:

This is the first line
This is the second line

But, with Java 13 and Text block you don't need to worry about "\n" and line breaks, you can get what you see. For example, you can write the same multi-line string using Java 13 text block as below:

String multiline = """This is the first line
This is the second line """;


4. SQL using Text Block

Another thing that could potentially benefit from Java 13 Text block feature is writing SQL queries. Similar to HTML and JSON, we, Java developers also write SQL queries for JDBC Statement and PreparedStatemet objects and this could potentially be a lot easier using Java 13, especially if you are writing queries that have VARCHAR values like below:

SQL in Java before Text blocks

String sql =
"SELECT title, price, owner" +
"FROM ITEM" +
"WHERE title = \'Effective Java\' +
"AND price < 20";


SQL in Java with Text blocks

String sql = """
SELECT title, price, owner
FROM ITEM
WHERE title = 'Effective Java'
AND price < 20
""";

You can see it's much more readable now. So, next time you write an SQL query in Java, don't forget to use the Text blocks feature, and if you are interested to learn more about new features introduced in Java 13 then you can further see What's New in Java 13 course on Pluralsight. 




Important points about Text Blocks in Java

Now that you know what is Text block of Java 13 and have seen some code written using text blocks in action. It's time to revise and know a couple of important points about text blocks

1. Text blocks are a preview feature in Java 13, which means they won't be available to you until you enable it while running Java. For example, you can enable all preview features from Java 13 by the following command:

$ java --enable-preview Java13

The --enable-preview switch will enable Java13 features including text blocks. Btw, the preview feature doesn't mean a half-baked feature, it means even though it's ready-to-use, finer details may change in the future.

2. Text blocks are still String data type which means you can store them inside String variable and apply all kinds of String functions like length(), toUpperCase(), trim(), contains(), and others.

3. You can concatenate text block with other regular String literals using the + operator, just like you do with regular string literals. For example, the following is a valid code in Java 13:

String data = """
Best
of
Both World
"""
+ "in" + """
Java 13""";


4. Text blocks also preserve formatting and elegantly handle whitespaces.


That's all about text blocks of Java 13. It's a really cool feature and I can see some popular uses of text blocks while declaring JSON, HTML, SQL, and multi-line strings in Java code. You can also use this when you have to escape sequence in your String. This will make your code much more readable. I know, this feature is already available for a long time in languages like Groovy but having this in Java is a totally different experience. While this is still a preview feature in Java 13, it's worth trying and using in code.

Further Learning
Java New Features (Java 8 to 12)
What's New in Java 15
Core Java Made Easy (Covers the latest Java 15) 


Other Java  and Programming Articles you May like

Thanks a lot for reading this article so far. If you like this article and Java text blocks then feel free to share with your friends and colleagues. If you have any questions or feedback then please drop a note, happy to answer any question you may have. 

No comments :

Post a Comment