In Java, there are situations where it is required to remove the unwanted white spaces that take unnecessary memory. These spaces can occur due to inappropriate formatting or some sort of encoded data. In such cases, the String “trim()” method in Java comes into effect that helps in removing these whitespaces to make the data clean, readable, and formatted.
How to Use the Java String “trim()” Method?
The String “trim()” method removes the whitespaces from both ends i.e., leading and trailing of the string without changing the original/default string. The Unicode value against the space character is “\u0020”. It is such that the “trim()” method analyzes this value before and after the string and removes the spaces based on it.
Note: The “trim()” method does not remove the spaces between the strings. For instance, the spaces in between the string “This is Javabeat” will not be omitted.
Syntax
public String trim()
Return Value
This method returns a string with the omitted starting/leading and ending/trailing white spaces.
How to Trim a String Correctly in Java?
Since Strings in Java are immutable objects, there is no approach to trim the strings in place. However, creating a new trimmed version of the string and returning it is the right approach which is done by the “trim()” method.
Internal Implementation of the String “trim()” Method in Java
Following is the internal implementation of the stated method:
public String trim() {
int strlen = value.length;
int count = 0;
char[] val = value;
while ((count < strlen) && (val[count] <= ' ')) {
count++;
}
while ((count < strlen) && (val[strlen - 1] <= ' ')) {
strlen--;
}
return ((count > 0) || (strlen < value.length)) ? substring(count, strlen) : this;
}
In this implementation, the string’s length is analyzed and then the string is traversed from both ends i.e., start and end. After that, the indexes of the first non-space character from both ends are fetched and the string without spaces is retrieved via the “substring()” method.
Example 1: Applying the String “trim()” Method in Java
This example applies the “trim()” method to remove the starting and ending whitespaces from the initialized string:
package jbArticles;
public class Trim {
public static void main(String[] args){
String x = " This is Java";
System.out.println("Given String -> "+x);
System.out.println("Trimmed String -> "+x.trim());
}}
Code Explanation
In this code, first, initialize the given string having leading and trailing white spaces and display it.
After that, apply the “trim()” method to remove the discussed spaces from the start and end of the string.
Output
In this output, it can be seen that the leading and trailing whitespaces from the given string are removed successfully as a trimmed string.
Example 2: Concatenating Strings Using “String.trim()” Method in Java
In this example, multiple strings comprising the white spaces at the start or end will be concatenated:
package jbArticles;
public class Trim {
public static void main(String[] args){
String first = "This ";
String second = " is ";
String third = "Java";
System.out.println("Strings Before (trim()) Method -> "+first + second + third);
System.out.println("Strings After (trim()) Method -> "
+first.trim() + second.trim() + third.trim());
}}
Code Explanation
- Initialize three strings having leading or trailing spaces.
- Now, concatenate all these strings via the “+” operator.
- Lastly, associate the “trim()” method with each string and concatenate all these strings.
Output
From this output, it can be observed that after applying the “trim()” method, the start and end white spaces are removed from the resultant string appropriately.
Example 3: Analyzing the Strings Length Before and After Trimming via the “trim()” Method
The whitespaces also contribute to the string length. Therefore, the following code demonstration checks for the length of the original as well as the trimmed string:
package jbArticles;
public class Trim {
public static void main(String[] args){
String x = " This is Java";
System.out.println("Given String -> "+x);
System.out.println("Given String Length -> "+x.length());
String y = x.trim();
System.out.println("Trimmed String -> "+y);
System.out.println("Trimmed String Length -> "+y.length());
}}
Code Explanation
- Likewise, initialize the string to be evaluated and return its length via the “length()” method.
- Now, apply the “trim()” method to trim the starting and ending whitespaces from the string.
- Finally, return the length of the trimmed string.
Output
From this outcome, the differences in length between the original and trimmed string can be clearly seen.
Example 4: Applying a Check Upon the String For Only White Spaces Using String “trim()” Method
The following code demonstration will check if the string comprises only the white spaces or not:
package jbArticles;
public class Trim {
public static void main(String[] args){
String givenString = " This is Java ";
if((givenString.trim()).length() > 0) {
System.out.println("The string has characters other than white spaces.");
}
else {
System.out.println("The string has white spaces only.");
}
givenString = " ";
if((givenString.trim()).length() > 0) {
System.out.println("The string has characters other than white spaces.");
}
else {
System.out.println("The string has white spaces only.");
}
}}
Code Explanation
- Similarly, initialize the string having the starting and ending white spaces.
- Now, apply the combined “trim()” and “length()” methods with the “if/else” statement to check if the string’s length equals zero after trimming the start and end white spaces.
- If so, the “if” statement executes. Otherwise, the “else” execution is carried out.
- Moving ahead, modify the defined string to white spaces only and repeat the same process via the “if/else” statement.
- In this case, since after trimming, the length of the string equals zero, the “else” condition is invoked.
Output
Before moving to the next example, overview the syntax of the “replaceAll()” method:
string.replaceAll(String reg, String repl)
In this syntax:
- “reg” represents the regex that needs to be replaced.
- repl” points to the replacement characters sequence.
Example 5: Difference Between “trim()” and “replaceAll()” Methods in Java
As discussed, the “trim()” method omits the starting and ending whitespaces from the string. The “replaceAll()” method, however, removes all the whitespaces from the start, end, and between the string. Below is the demonstration:
package jbArticles;
public class Trim {
public static void main(String[] args) {
String givenString = " This is Java ";
System.out.println("Given String \n"+ givenString);
System.out.println("\nString after Applying 'trim()' Method \n"+ givenString.trim());
System.out.println("\nString after Applying 'replaceAll()' Method \n"+ givenString.replaceAll("\\s",""));
}}
Code Explanation
- Declare the string and display it.
- In the next step, apply the “trim()” method to trim the string based on the leading and trailing whitespaces.
- Now, implement the “replaceAll()” to replace all the whitespaces in the string with the empty string specified as its second parameter.
Output
The difference between the methods applied on the string can be observed in the above outcome.
Conclusion
The String “trim()” method removes the whitespaces from both ends i.e., leading and trailing of the string without changing the original/default string. However, this method does not omit the spaces between the strings. It can be used to concatenate the strings by omitting the white spaces or can be applied to check if the string contains only whitespaces.