Trusted answers to developer questions

How to use Java's string trim() method

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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);
}
}

RELATED TAGS

java
string
trim
method
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?