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:
1 |
public String trim() |
The trim( ) method is quite useful when you process user commands.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package net.javaforyou.corejava.string; public class StringTrimMethodDemo { public static void main(String[] args) { String str = " This is trim() method demo "; System.out.println("str : " + str); //apply trim() method on String str. System.out.println("str : " + str.trim()); } } |
Output:
1 2 |
str : This is trim() method demo str : This is trim() method demo |
If you observe the output, the leading and trailing whitespaces have been removed after applying trim() method on String str.
Other posts: