Java string trim() method

In this post we are going to learn java string trim() method.

java string trim() method

Trim() method removes trailing and leading spaces from a string.

Also read – string length() method in java

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than ‘\u0020’ (the space character), then a reference to this String object is returned.

Syntax :

public String trim()

Here trim method does not accept parameters.

Trim method returns the string with deleted spaces.

public class TrimJava
   public static void main(String[] args)
      String strOriginal = " Great Barrier Reef  ";
      String strTrimmed = strOriginal.trim();
      System.out.println("Before : " + strOriginal);
      System.out.println("After : " + strTrimmed);

Output :

Before :   Great Barrier Reef
After : Great Barrier Reef


  • trim() method in java uses unicode value, that is, \u0020.
  • unicode value is checked before and after a string.
  • trim() method in java does not remove middle spaces, that is, for example there is a string “Core Java” so the space between “Core” and “Java” will not be eliminated.