Java String trim() method example

java.lang.String trim()

Description :

This java tutorial shows how to use the trim() method of String class of java.lang package. This method returns a new String which is a exact value of the original String stripped with leading and trailing spaces.

Method Syntax :

public String trim()

Parameter Input :

Method Returns :

The trim() method of String class returns a new String object. The method returned value is a copy of the original String with leading and trailing spaces omitted.

Compatibility Version :

Requires Java 1.4 and up

Exception :


Discussion :

The trim() method of String class is a way to normalize the string input which sometimes have a trailing and leading white spaces. These white spaces messes with our logic and display of these information. I have encountered many instances where my code logic fails because of white spaces on a String.

By invoking the trim() method, it returns a new String object. It doesn’t replace the value of String object. Thus if we want to have access to the new String object, we just need to assign it to a new variable or reassign it to the old String.

Java Code Example :

This example source code demonstrates the use of trim() method of String class to remove the leading and trailing spaces.

Sample Output :

Running the trim() method example source code of String class will give you the following output

string trim method example

string trim method example

Exception Scenario :


Suggested Reading List :

References :

Comments are closed