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.

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading