English 中文(简体)
Java 12 - String methods
  • 时间:2024-12-22

Java 12 - String methods


Previous Page Next Page  

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

indent(n) method

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

Usage


string.indent(n)

    n > 0 - insert space at the begining of each pne.

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

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

    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;

pubpc class APITester {
   pubpc static void main(String[] args) {
      String str = "Welcome 
to 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