Java String stripTrailing()

In this guide, you will learn about the String stripTrailing() method in Java programming and how to use it with an example.

1. String stripTrailing() Method Overview


The stripTrailing() method is a member of the Java String class, introduced in Java 11. It is utilized to eliminate all trailing whitespace characters from a given string, based on the Unicode Character Property “White_Space”. The method is more comprehensive than trim(), which only removes space characters, as it deals with any Unicode whitespace character.


public String stripTrailing()


The stripTrailing() method does not take any parameters.

Key Points:

- It removes all types of trailing whitespaces as per the Unicode standard.

- The method returns the original string if there are no trailing whitespaces.

- It doesn’t affect leading whitespaces.

2. String stripTrailing() Method Example

public class StripTrailingExample {
    public static void main(String[] args) {
        String str = " \t  \u2005Java\u2005   \n";
        String strippedString = str.stripTrailing();
        System.out.println("Original String: [" + str + "]");
        System.out.println("String with Trailing Whitespaces Stripped: [" + strippedString + "]");


Original String: [ 	  Java 
String with Trailing Whitespaces Stripped: [ 	  Java]


In this example, a string str is defined with different types of whitespaces (tabs, spaces, and the Unicode character \u2005 - Four-Per-Em Space) surrounding the word "Java". 

The stripTrailing() method is invoked to remove all trailing whitespaces while leaving the leading whitespaces intact. The resultant modified string is then outputted to the console, illustrating the effectiveness of the stripTrailing() method.