Java 13

Java 13 – Text Blocks

Java 13 introduces text blocks to handle multiline strings like JSON/XML/HTML etc. It is a preview feature.

  1. Text Block allows to write multiline strings easily without using \r\n.
  2. Text Block string have same methods as string like contains(), indexOf() and length() functions.

Example

Consider the following example −

Java13TextBlock.java

public class Java13TextBlock {

   public static void main(String[] args) {
      String stringJSON = "{\r\n" 
         + "\"Name\" : \"Elavarasan\",\r\n" 
         + "\"RollNO\" : \"12\"\r\n" 
         + "}";  
   
      System.out.println(stringJSON);
	  
	  String textBlockJSON = """
         {
            "name" : "Elavarasan",
            "RollNO" : "12"
         }
         """;
      System.out.println(textBlockJSON);
	  
	  System.out.println("Contains: " + textBlockJSON.contains("Elavarasan"));
	  System.out.println("indexOf: " + textBlockJSON.indexOf("Elavarasan"));
	  System.out.println("Length: " + textBlockJSON.length());
   }   
}

Output

Compile the class using javac compiler as follows −

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

>java --enable-preview Java13TextBlock

It should produce the following output −

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

Contains: true
indexOf: 15
Length: 45

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs