Core Java

JEP 355 Text Blocks in JDK 13

JDK 13 went GA on September 17th, 2019 and the prominent new features are listed here. One of the new features is “text blocks”. This allows writing multiline strings easily without the need for concatenation while splitting into different lines.

Lets quickly look at the different ways of creating multiline strings:

String aBlock = """
SELECT id, first_name, last_name, dob
FROM person
WHERE id = ?
""";

String aIndentedBlock = """
    SELECT id, first_name, last_name, dob
    FROM person
    WHERE id = ?
""";

String anotherBlock = """
SELECT id, first_name, last_name, dob
FROM person
WHERE id = ?""";

System.out.print(aBlock);
System.out.print(aIndentedBlock);
System.out.print(anotherBlock);
System.out.println("This comes in the same line");

These are some of the invalid ways to write multiline string:

//        String thisIsInvalid = """This is invalid""";
//        String thisIsALsoInvalid = """THis is also invalid
//        """;

The text cannot start immediately after the opening quotes of the block i.e `”””` instead it has to start in the next line.

We can include “, ‘ in the multiline string:

System.out.println("""
        Block containing "" ' '
        """);

The end of block quotes can end in the same line as the text of in a new line:

String thisIsValid = """
This is valid""";

The complete code for this can be found here.

Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: JEP 355 Text Blocks in JDK 13

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button