Java 13 - Text Blocks (JEP 355)

Text blocks allows us to create multiline strings easily. It allow a better way of writing, and more importantly reading, multi-line text inside Java code. The multiline string has to be written inside a pair of triple-double quotes.

This feature allow us to write code from other languages inside our Java code. Previously, you would always need boilerplate like /n for line breaks at the end of every line, which makes code error-prone and hard to read. Here example to build strings for HTML, JSON, and SQL:

JEP355TextBlocks.java
public class JEP355TextBlocks {

    public static void main(String[] args) {

        // text blocks for html
        String html = """
                      <html>
                          <body>
                              <p>Hello, fellow programmers</p>
                          </body>
                      </html>
                      """;
        System.out.println(html);
        
        // text blocks for json
        String json = """
            {
                "firstName": "Regina",
                "lastName": "Poetri",
                "age": 20
            }
            """;
        System.out.println(json);
        
        // text blocks for sql
        String sql = """
               SELECT FIRST_NAME, LAST_NAME, BIRTH_DATE
               FROM CUSTOMER
               WHERE CUSTOMER_ID = ?
               """;
        System.out.println(sql);
    }
}
                    

And when we run it:

<html>
    <body>
        <p>Hello, fellow programmers</p>
    </body>
</html>

{
    "firstName": "Regina",
    "lastName": "Poetri",
    "age": 20
}

SELECT FIRST_NAME, LAST_NAME, BIRTH_DATE
FROM CUSTOMER
WHERE CUSTOMER_ID = ?

We can use this feature for any "Polyglot" language inside our Java code. This is better than concat String that we always use before:

String sql = "SELECT FIRST_NAME, LAST_NAME, BIRTH_DATE\n" +
       "FROM CUSTOMER\n" +
       "WHERE CUSTOMER_ID = ?\n";
                    

This feature is still a preview feature in Java 13.

New Methods in String Class for Text Blocks

There are three new methods in the String class, associated with the text blocks feature:

  • String formatted​(Object... args): Formats using this string as the format string, and the supplied arguments.
  • String stripIndent(): Returns a string whose value is this string, with incidental white space removed from the beginning and end of every line.
  • String translateEscapes(): Returns a string whose value is this string, with escape sequences translated as if in a string literal.

Those methods are associated with text blocks, a preview language feature. Text blocks and/or those methods may be changed or removed in a future release. Those why those APIs marked as Deprecated, for removal.

JEP355StringMethods.java
public class JEP355StringMethods {

    public static void main(String[] args) {

        String firstName = "Josefo";
        String lastName = "Gaho";
        String email = "[email protected]";
        
        String sql = """
               insert into CUSTOMER(FIRST_NAME, LAST_NAME, EMAIL)
               values ('%s', '%s', '%s')
               """.formatted(firstName, lastName, email);
        System.out.println(sql);
        
        String s = "   Line 1\n" +
           "       Line 2\\n" +
           "   Line 3\n";
        System.out.println("Without stripIndent():");
        System.out.println(s);
        
        System.out.println("With stripIndent():");
        System.out.println(s.stripIndent());
        
        System.out.println("With stripIndent() and translateEscapes():");
        System.out.println(s.stripIndent().translateEscapes());
    }
}
                    

Will result:

insert into CUSTOMER(FIRST_NAME, LAST_NAME, EMAIL)
values ('Josefo', 'Gaho', '[email protected]')

Without stripIndent():
   Line 1
       Line 2\n   Line 3

With stripIndent():
   Line 1
       Line 2\n   Line 3

With stripIndent() and translateEscapes():
   Line 1
       Line 2
   Line 3

Conclusion

Overall it’s a great preview. It’s good to see the much-awaited text blocks String support, especially since other languages that run on JVM, like Kotlin and Scala, have had support for multi-line text for quite some time now. It's a very useful feature, especially for us who working with "in-line" code like SQL or JSON. I'm looking forward for full-release version.

Reference: Programmer's Guide To Text Blocks

This article is part of What is New in Java 13 Series.

Other articles in this series: