Java 13 - Text Block Methods


Advertisements

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.

  • stripIndent() - removes incidental white spaces from the start and end of the string.

  • translateEscapes() - translate the escape sequences as per the string syntax.

  • formatted() - similar to String format() method to support formatting in text block strings.

Example

Consider the following 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);
   }   
}

Compile 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

Useful Video Courses


Video

Java Date and Time Online Training

16 Lectures 2 hours

Malhar Lathkar

Video

Java Servlet Online Training

19 Lectures 5 hours

Malhar Lathkar

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

Java Online Training

Most Popular

126 Lectures 7 hours

Tushar Kale

Video

Java Essential Training

119 Lectures 17.5 hours

Monica Mittal

Video

Java Essentials Online Training

76 Lectures 7 hours

Arnab Chakraborty

Advertisements