Java String trim() method

Let’s learn java String trim() method.

Java string trim() method

String trim() method removes leading and trailing whitespaces from a string. This whitespace or space character unicode value is ‘\u0020’.

java string trim() method

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.

Let’s see an example on 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:

  • trim() method does not remove middle spaces, that is, for example there is a string “Hello World”, space between “Hello” and “World” will not be trimmed or removed.

Also read – ArrayList in java