Text Blocks In Java 15

  • Post last modified:July 16, 2022
  • Reading time:2 mins read

Introduction

  • A Text Block is a multi-line string literal that avoids the need for most escape sequences.
  • In another word, its makes multi-line string literals more readable.
  • Text Block is created with the goal of
    – Simplifying the task of writing a java program by making it easy to express strings that span several lines of source code
    – Enhance the readability of strings that denotes code written in non-java languages such as HTML, SQL, Javascript, etc.
  • It was released as preview in java 13 & 14 but from java 15 it is standard feature.

Use Cases

  • The best way to explain would be to consider how we embed a snippet of HTML, XML, SQL, or JSON in a string literal.
  • For example,
Text Block
"""
line 1
line 2
line 3
"""This is equivalent to "line 1\n" +
"line 2\n" +
"line 3\n"
  • We often see SQL strings like below in the DAO layer, which when executed on the database either through the JPA provider or directly with PreparedStatement bypassing JPA.
String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
               "WHERE `CITY` = 'INDIANAPOLIS'\n" +
               "ORDER BY `EMP_ID`, `LAST_NAME`;\n";
  • Now with Text Block, we can write the above query in a more readable format and don’t need to provide a newline character and don’t need to provide an escape character.
  • We can use three double-quote characters (""") followed by zero or more whitespaces followed by a line terminator. We can close the string with three double-quote characters.
String query = """
               SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
               WHERE `CITY` = 'INDIANAPOLIS'
               ORDER BY `EMP_ID`, `LAST_NAME`;
               """;
  • The above example might not look a great deal to some, since the example is very simple but if think when we have a very complex String for example below JSON string, and if we write this JSON as String literal it would not be much readable.

  • If we represent it as String in Java without Text Block, then it would not be so developer-friendly.
  • But if we use java Text Block then, it looks more developer-friendly and much more readable.

Conclusion

  • With Text Block java readability increased further. Since Java 8 , Java designers have worked alot towards making java less versbose and more readable , Text Block is also one of such effort.
  • This is not the game changer feature but its java designers commitment to make this #1 language more readable and reduce verbosity.

Leave a Reply