Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java string trim() method is used to return a string which is trimmed version of the specified string. It removes whitespaces from both end of the specified string.

Syntax

public String trim()

Parameters

No parameter is required.

Return Value

Returns the trimmed version of the specified string.

Exception

NA.

Example:

In the below example, trim() method to used to return the trimmed version of the string called MyString.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "    Hello World!.    ";
    String NewString = MyString.trim();

    System.out.println(NewString);
  }
}

The output of the above code will be:

Hello World!.

❮ Java String Methods