The trim() method of a string class in Java eliminates the leading and trailing spaces from the string. This method checks for the Unicode of the space character at the start and end of the string. After removing the spaces, it returns an updated string.
Method signature:
The signature for a trim() method is as shown below.
public String trim()
Method parameters and return type:
Return type: It returns a string excluding the spaces.
Parameters: It doesn’t take any parameters.
Throws: It throws a NullPointerException if the string is null.
Example:
In the first example, we tested the output of a string with and without the trim() method.
Source code:
public class Example1{
public static void main(String args[]){
String str=" Java tutorial at ";
System.out.println(str+"online tutorial point");
System.out.println(str.trim()+"online tutorial point");
}
}
Output:
run:
Java tutorial at online tutorial point
Java tutorial atonline tutorial point
BUILD SUCCESSFUL (total time: 7 seconds)
Example:
Here we have tested the length of a string before and after using a trim() method.
Source code:
public class Example2 {
public static void main(String[] args) {
String str = " this is a trim tutorial ";
System.out.println("Length before trimming: " + str.length());
System.out.println(str);
String trimString = str.trim();
System.out.println("Length after trimming: "+trimString.length());
System.out.println(trimString);
}
}
Output:
run:
Length before trimming: 28
this is a trim tutorial
Length after trimming: 23
this is a trim tutorial
BUILD SUCCESSFUL (total time: 2 seconds)