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.

Advertisements

Categories: Java, JDK 13

Tagged as:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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