Java String trim() method example

HQ » Java Tutorial » java.lang » String » trim() method example
Java String trim() method example 2018-02-19T13:11:26+00:00

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 :

DataType Parameter Description
N/A N/A N/A

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 :

None

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 :

N/A

Suggested Reading List :

References :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close