logo

Test Block Methods


Show

Java 12 launches text blocks to manage multiline strings such as JSON/XML/HTML etc and adds new ways to string class to manage text blocks. It is a preview attribute.

  • stripIndent() - detach incidental white spaces from the beginning and at the last of the string.
  • translateEscapes() - convert the escape sequences as per the string syntax.
  • formatted() - same to String format() way to assist formatting in-text block strings.

Example

Examine the below-given example:-

ApiTester.java

public class APITester {

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

Assemble and Run the Program

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


Output

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

Contains: true
indexOf: 15
Length: 45