Java 13

Java 13 – Text Block Methods


Java 12 introduces text blocks to handle multiline strings like JSON/XML/HTML etc and added new methods to String class to handle text blocks. It is a preview feature.

  1. stripIndent() – removes incidental white spaces from the start and end of the string.
  2. translateEscapes() – translate the escape sequences as per the string syntax.
  3. formatted() – similar to String format() method to support formatting in text block strings.

Example

Consider the following example −

Java13TextBlockMethod.java

public class Java13TextBlockMethod {

   public static void main(String[] args) {
	  String textBlockJSON = """
         {
            "name" : "%s",
            "RollNO" : "%s"
         }
         """.formatted("Elavarasan", "12");
      System.out.println(textBlockJSON);
   }   
}

Output

Compile the class using javac compiler as follows −

>javac -Xlint:preview --enable-preview -source 13 Java13TextBlockMethod.java

>java --enable-preview Java13TextBlockMethod

It should produce the following output −

{
"Name" : "Elavarasan",
"RollNO" : "32"
}
{
   "name" : "Elavarasan",
   "RollNO" : "32"
}

Contains: true
indexOf: 15
Length: 45

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs