logo

String Methods


Show

New ways to string for easy formatting are introduced in Java 12. Some of them are given below:

indent(n) Method

Alter the indention of each and every line of string established on the argument passed.

Usage

string.indent(n)
  • n > 0 - insert space at the starting of each line.
  • n < 0 - delete space at the starting of each line.
  • n < 0 and n < available spaces - delete all leading spaces of each line.
  • n = 0 - no change or replacement.

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

Modify a string to give the output as R.

Usage

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

Optional<String> describeConstable() method

Returns Optional Object having a definition of string instance.

Usage

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

resolveConstantDesc​(MethodHandles.Lookup lookup) method

Gives back descriptor instance string of available string

Usage

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

Examine the Below-Given 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