Close

Java 13 - Text Blocks (JEP 355)

[Updated: Oct 26, 2019, Created: Oct 25, 2019]

In Java 13, a text block is:

  • a multi-line string literal that can be written without + concatenation
  • avoids the need for most escape sequences. That means we don't have to escape character like double quote (")
  • automatically formats the string in a predictable way, and gives the developer control over format when desired

This is a preview language feature in JDK 13.

Opening and closing delimiter

In a text block, the opening delimiter is a sequence of three double quote characters (""") followed by zero or more white spaces followed by a line terminator. The content begins at the first character after the line terminator of the opening delimiter.

The closing delimiter is a sequence of three double quote characters. The content ends at the last character before the first double quote of the closing delimiter.

package com.logicbig.example;

public class TextBlockExample1 {
  public static void main(String[] args) {
      String inputElement = """
                            Name: Jenny
                            Phone: 8675309
                            age: 35
                            """;

      System.out.println(inputElement);
  }
}
Name: Jenny
Phone: 8675309
age: 35

Starting text on the same line as """ is a compile time error:

String inputElement = """Name: Jenny
                              Phone: 8675309
                              age: 35
                              """;
illegal text block open delimiter sequence, missing line terminator

Relative left alignment

From each line, the left side white spaces are removed till the position of the line which has the least left side spaces:

package com.logicbig.example;

public class TextBlockExample2 {
  public static void main(String[] args) {
      String inputElement = """
                            Name: Jenny
                        Phone: 8675309
                            age: 35
                            """;

      System.out.println(inputElement);
  }
}
    Name: Jenny
Phone: 8675309
age: 35

Above also applies to the closing """

package com.logicbig.example;

public class TextBlockExample3 {
  public static void main(String[] args) {
      String inputElement = """
                            Name: Jenny
                            Phone: 8675309
                            age: 35
                      """;

      System.out.println(inputElement);
  }
}
      Name: Jenny
Phone: 8675309
age: 35

Example Project

Dependencies and Technologies Used:

  • JDK 13
Java 13 - Text Blocks Select All Download
  • text-blocks-intro
    • src
      • com
        • logicbig
          • example
            • TextBlockExample1.java