Java String trim() Method

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

This is one of the articles from our Java Tutorial for Beginners.


Java String trim() Method

The java string trim() method gets rid of all the spaces before and after the String.

Syntax

It will make more sense in an example.

Example

If you run this code on your computer, you'll see the following in the console:

There's no place like home.

There's no place like home.

Commentary

  • As you see, we have 2 variables which are called sentence1 and sentence2. The same sentence ("There's no place like home.") is assigned to both of these variables. I would like to draw your attention that we have spaces at the beginning and end of the sentence "There's no place like home."
  • To display the sentence "There's no place like home." without any leading and trailing spaces, we have to apply the Java String trim() method.

When we write these 2 lines of code,

we get the following in the console:

There's no place like home.

There's no place like home.

Sentence1 is displayed in the console with leading and trailing spaces, while sentence2 is displayed without these spaces, because we applied the Java String trim() method to it.

As you see, it's all very simple.

You can find more articles in our Java Tutorial for Beginners. 

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--