What is String.strip in Java?

Overview

strip() is an instance method that returns a string whose value is the string with all leading and trailing white spaces removed. This method was introduced in Java 11.

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

Example

In the below code, we define three strings. One has only white spaces, one has leading and trailing white spaces with characters in it, and one has only trailing white spaces. The output will be as follows.

"    " - ""
"   hello    " - "hello"
"h i  " - "h i"

Code

public class Main {

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

Free Resources