Java string trim() method

Let’s learn java string trim() method.

java string trim() method

Java string trim() method

This method removes trailing and leading spaces from a string.

Also read – major features of 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()

This method does not accept parameters.

Returns: 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


NOTE:

  • this method uses unicode value, that is, \u0020.
  • unicode value is checked before and after a string.
  • this method 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.