Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
trim
method

How to use Java's string trim() method

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring