Java String strip() Method Tutorial

In this section, we will learn what the String strip() method is and how to use it in Java.

What is Java String strip() Method?

The Java String strip() method is used to remove any white space from the leading and trailing parts of a string value.

Notes:

  • The method does not change the original value and just returns a new string as a result.
  • If the target string contains only white spaces, then an empty string will return as a result of calling this method.

Java strip() Method Syntax:

public String strip();

strip() Method Parameters:

The method does not take an argument.

strip() Method Return Value:

The return value of this method is the stripped copy of the target string that this method is called upon.

strip() Method Exceptions:

The method does not throw an exception.

Example: using String strip() method

public class Main {
    public static void main(String[] args) {

        String input = "   hello   ";
        System.out.println("Input string length: " + input.length());
        String stripStr = input.strip();
        System.out.println("Stripped string length: " + stripStr.length());
    }
}

Output:

Input string length: 11

Stripped string length: 5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies