Java 12 - String methods


Advertisements

Java 12 introduces following new methods to String for easy formatting.

indent(n) method

Adjust the indention of each line of string based on argument passed.

Usage

string.indent(n)
  • n > 0 - insert space at the begining of each line.

  • n < 0 - remove space at the begining of each line.

  • n < 0 and n < available spaces - remove all leading space of each line.

  • n = 0 - no change.

transform(Function<? super String,​? extends R> f) method

Transforms a string to give result as R.

Usage

String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());

Optional<String> describeConstable() method

Returns Optional Object containing description of String instance.

Usage

Optional<String> optional = message.describeConstable();

resolveConstantDesc​(MethodHandles.Lookup lookup) method

Returns descriptor instance string of given string.

Usage

String constantDesc = message.resolveConstantDesc(MethodHandles.lookup());

Consider the following example −

ApiTester.java

import java.lang.invoke.MethodHandles;
import java.util.Optional;

public class APITester {
   public static void main(String[] args) {
      String str = "Welcome \nto Tutorialspoint!";
      System.out.println(str.indent(0));
      System.out.println(str.indent(3));

      String text = "Java";
      String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
      System.out.println(transformed);

      Optional<String> optional = text.describeConstable();
      System.out.println(optional);

      String cDescription = text.resolveConstantDesc(MethodHandles.lookup());
      System.out.println(cDescription);
   }
}

Output

Welcome 
to Tutorialspoint!

   Welcome 
   to Tutorialspoint!

avaJ
Optional[Java]
Java
Advertisements