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() + "\"");
    }
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources