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

Signature of trim() Method:

public String trim()

Let’s understand it through a demo program.

Example1: Java String trim() method

package com.masterjavatutorial;
public class Test {
   public static void main(String[] args) {
	String str="  HelloWorld  ";
	System.out.println("String length = "+str.length()); 
	String str1 = str.trim();
	System.out.println("String length = "+str1.length());
   }
}

Output of the above program is as below:

String length = 14
String length = 10

We can see here that leading and trailing whitespaces are removed. After trim() method is applied on the string with trailing and leading whitespaces, the length of the string gets reduced. This is evident from the output of the program.

Example2: Java String trim() method

trim() method does not remove while space if present in between the strings (not trailing and leading spaces).

package com.masterjavatutorial;
public class Test {
   public static void main(String[] args) {
	String str="Hello World";
	System.out.println("String length = "+str.length()); 
	String str1 = str.trim();
	System.out.println("String length = "+str1.length());
   }
}

output of the above program is as below:

String length = 11
String length = 11

We can see in this case that the length of the string remains same even after applying trim() method. This certify the fact that trim() method does not remove while space if present in between the strings (not trailing and leading spaces).