Java string trim() method

Let’s learn java string trim() method.

java string trim() method

Java string trim() method

String trim() 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()

String trim() 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:

  • String trim() 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.

whitespace

Now let’s learn to trim whitespace. trim() method returns a string whose value is this string, with any leading and trailing whitespace removed, or this string if it has no leading or trailing white space.

Also read – java string methods

Let’s see an example,

public class StringTrimDemo 
{
   public static void main(String[] args) 
   {
      String str1 = "  xyz  abc \t\t ";
      System.out.println("$$$" + str1 + "$$$");
      String str2 = str1.trim();
      System.out.println("$$$" + str2 + "$$$");
   }
}



Output:

$$$ xyz abc $$$
$$$xyz abc$$$