How to use Java's string trim() method

The trim() method in Java eliminates leading and trailing whitespaces in a string. Here is how the method is defined:

public String trim()

The method takes no parameters, returns a string, and can be called by any string. However, trim() will not alter the original string; a new trimmed string will be returned instead.

Below ​is a copy of the original string with its whitespaces removed.

svg viewer

Code

The following code snippet demonstrates the usage of the trim() method:

class Program {
public static void main( String args[] ) {
String str = " the quick brown fox ";
System.out.println("String with whitespaces: " + str);
String trimmedStr = str.trim();
System.out.println("Trimmed string: " + trimmedStr);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved