For every release, API methods are added to java classes. This tutorial shows you new methods added to the java15 version.

Java15 String methods

In java15, the following methods are added to the String class

  • formatted() method
  • stripIndent() method
  • translateEscapes() method

String formatted() method

the formatted() method used to format the string and replace it with arguments.

    public String formatted(Object... args) 

Arguments: takes multiple arguments that replace the value with a formatted string Returns: Returns formatted string.

Here is an example code

public class Test {
    public static void main(String[] args) {
        System.out.println("1. %s 2. %s 3. %s ".formatted("one", "two", "three"));
    }
}

Output:

1. one 2. two 3. three 

String stripIndent() method in java

The stripIndent method removes the whitespaces from the start and end of a string line.

It does not remove the white space in the middle of the string.

Syntax:

stripIndent()

No Arguments. It removes new strings by removing whitespaces from the beginning and end of a string.

public class Test {
    public static void main(String[] args) {
        System.out.println("   hello world".stripIndent());
        System.out.println("hello world  ".stripIndent());
        System.out.println("   hello world  ".stripIndent());
    }
}

Output:

hello world
hello world
hello world

String translateEscapes() method in java

translateEscapes method returns a new string which translates the escape characters into a string literal.

Escape characters are tab (\t), new line(\n) etc.. Syntax:

translateEscapes()

Return new string with translated escape characters into a string literal.

Here is an example

public class Test {
    public static void main(String[] args) {
        String str = "This is tab \t, Next New Line \n,next backspace \b,next Single Quotes \' next,Double Quotes \" ";
        System.out.println(str.translateEscapes());
    }
}

Output:

This is tab  , Next New Line 
,next backspace,next Single Quotes ' next,Double Quotes "