Java String trim() method

In this tutorial, we will learn about Java String trim() method.

String class in Java provides trim() method to remove the leading and trailing whitespaces in a String. The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed.
The syntax of trim() method is:

Syntax of trim() method:

The trim( ) method is quite useful when you process user commands.

Example:

Output:

If you observe the output, the leading and trailing whitespaces have been removed after applying trim() method on String str.

Other posts: