logo

Text Blocks 


Show

In, Java 13 text blocks are released to manage multiline strings such as JSON/XML/HTML, etc as it has the preview attribute. With Java 14, there is a second preview of text blocks.

Below are some enhancements in Text Block:

  • \ − specify an end of the line in case a new line is to be introduced.
  • \s − specify a single space.

Example

Examine the below-given example

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      String stringJSON = "{\r\n" 
         + "\"Name\" : \"Mahesh\"," 
         + "\"RollNO\" : \"32\"\r\n" 
         + "}";  

      System.out.println(stringJSON);
      String textBlockJSON = """ {"name" : "Mahesh", \ "RollNO" : "32" } """;
      System.out.println(textBlockJSON);

  System.out.println("Contains: " + textBlockJSON.contains("Mahesh"));
  System.out.println("indexOf: " + textBlockJSON.indexOf("Mahesh"));
  System.out.println("Length: " + textBlockJSON.length());
   } 
}

Compile and Run The Program

$javac -Xlint:preview --enable-preview -source 14 APITester.java

$java --enable-preview APITester

Output

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

Contains: true
indexOf: 15
Length: 45