Java string trim() method

Let’s learn java string trim() method.

Java string trim() method

Java String trim() method removes leading and trailing whitespaces from a string.

java string trim() method

This whitespace or space character unicode value is ‘\u0020’.

trim() method checks space character before and after the given string.

If it exists then trim() method removes whitespaces and returns the string.

Syntax:

public String trim()

Parameters:

N/A

Returns:

a string with all leading and trailing space removed, or this string if it has no leading or trailing space.

Also read – java string methods

Let’s see an example on java String trim() method.

public class StringTrimJava
{
   public static void main(String[] args)
   {
      String str = "     welcome to helloworld java!        ";
      System.out.println(str);
      System.out.println(str.trim());
   }
}


Output:

welcome to helloworld java!

welcome to helloworld java!


NOTE:

  • this method does not remove middle spaces, that is, for example there is a string “Core Java”, space between “Core” and “Java” will not be trimmed or removed.

Also read – how to rename file in java


string strip method

strip() method of String class was introduced in Java 11. Since Java 11 String class has three more methods to remove extra whitespaces.

Here are three methods of String class to remove extra whitespaces.

  1. String strip(): returns a string whose value is this string, with all leading and trailing white space removed.
  2. String stripLeading(): returns a string whose value is this string, with all leading whitespace removed.
  3. String stripTrailing(): returns a string whose value is this string, with all trailing whitespace removed.

Now let’s see an example on java string strip() method.

public class StringStripMethod
{
   public static void main(String[] args)
   {
      String strInput = "    Flower Brackets !!    ";
      System.out.println(strInput.strip());
      System.out.println(strInput.stripLeading());
      System.out.println(strInput.stripTrailing());
   }
}


Output:

“Flower Brackets !!”
“Flower Brackets !! “
” Flower Brackets !!”


java string trim vs strip

String trim() and strip() methods both remove trailing and leading whitespaces from a string.

But strip() method uses Character.isWhitespace() method which determines if the specified character (Unicode code point) is white space according to java.

While trim() method removes space which is less than or equal to ‘\u0020’ (the space character).