What is Java trim method?

The trim() method of Java can be used for removing the whitespaces from left and right of the given string.

The leading or trailing spaces may occur particularly, as you are taking user input. Similarly, for database driven strings, you may ensure the strings does not include the leading or trailing spaces by using the trim() method.

A trim example trimming left

Syntax of trim Java method

Following is the general syntax for using the trim method:


  • Where Str is the Java string that you want to remove space from.
  • If the specified string contains leading and/or trailing spaces, the trim() returns a copy of the string with whitespaces omitted.
  • If specified string does not contain a leading or trailing whitespace, it returns this string.
  • Basically, trim() function checks the ‘\u0020’ Unicode character which represents space character.

An example of Java string trim method

In the following example, a string is created with leading and trailing spaces. After that, the trim method is used and the string is displayed. For making things clear, the string before and after using the trim method is displayed so you may see the difference:

See online demo and code

The output:

java trim string

You can see, the leading and trailing spaces are removed from the specified string.

Using the \t (tab) with trim method example

Yes, the trim() function will also remove spaces created due to \t i.e. tab. See the following example where a string is created with \t towards both sides. Again, for clarification, the original string is displayed along with the copy returned after using the trim():

See online demo and code

trim tabs

What about trimming only left or right spaces?

Well, as we have seen in the definition and examples, the trim method can be used for removing the leading and trailing spaces. However, in certain scenarios, you may require omitting whitespaces from one side – left or right of the string.

There is no specific method for that like ltrim to remove leading spaces or rtrim for removing the trailing space. In other programming languages like Python, you may use the lstrip or rstrip methods for that. So, how to do this in Java?

You may use different ways and one of the ways is using the replaceAll method as shown in the example below:

See online demo and code

remove leading trail

You can see four strings as output:

  • The first is the original string with a concatenated string to display spaces towards the right side.
  • The second string used trim() function, so removed spaces from both sides.
  • In the third string, the leading spaces (from the left side) are removed. You can see three spaces between the original and concatenated string towards the right side.
  • Similarly, the last statement displays the string with spaces removed from the right side only.