What is String.stripTrailing in Java?

Overview

stripTrailing() is an instance method that returns a string whose value is this string, with all trailing white spaces removed. Trailing means it is at the end of the string. This method was introduced in Java 11.

If the string contains only white spaces, then applying this method results in an empty string.

Example

In the code below, we define a string with trailing spaces. Next, we apply the stripTrailing() method on the string to remove the trailing whitespace.

The code will print hello.

public class Main {

    public static void main(String[] args) {
        String s = "hello   ";
        System.out.println(s.stripTrailing());
    }
}

In the code below, we define a string with leading and trailing white spaces. When the stripTrailing() method is applied, only trailing white spaces will be removed.

The code will print " hello"

public class Main {

    public static void main(String[] args) {
        String s = "    hello     ";
        System.out.println("\"" +s.stripTrailing() + "\"");
    }
}

Free Resources