Updated December 16, 2023
Introduction to trim() Function in Java
The following article, trim() Function in Java, outlines the functions in Java. Java’s trim method gets rid of leading and trailing spaces. It is a built-in function. This method takes any string as input and checks if it has any space character before and after the string, and then deletes the unnecessary white spaces wherever found and returns the edited string.
Java is a widely used and easy-to-learn programming language; many methods and functions are available to ease the task. The trim method is one such method. As defined in Oracle Docs, the trim method returns a copy of the string, excluding leading and trailing whitespace. In simple terms, the trim method removes whitespaces from the beginning and end of a string.
Table of Content
- Introduction
- How does the trim() method work?
- Examples of trim() Functions in Java
- Difference between trim() method and replaceAll() method
- Best practices for using trim() in Java
Let us now understand the standard syntax used for the implementation of the Trim method:
Syntax:
public String trim()
The above-mentioned is the standard syntax for the trim method. Also known as Signature, it takes no parameters, and this trim method returns the edited string.
How does the trim() method work?
A trim method in Java is a built-in function. The Unicode Value for white space in Java is “\u0020”. When passing any string, the trim method checks for the mentioned Unicode Value for white space. If the Trim method finds a matching Unicode Value, then it eliminates that and returns the newly trimmed string. It is also important to understand that this method does not delete or trim any middle spaces. Whenever the trim method is called, a new string object is returned.
Often, trim is unnecessary, and if the trim is removed in unwanted situations, it will improve the program’s performance. The trim method cannot be used when handling whitespaces between or inside the string. Regular expressions are a better choice for such problems.
Now that we have learned the definition and the standard syntax for the trim method and understand how trim works, let’s see a trim method in action with some programs.
Examples of trim() Functions in Java
We will now demonstrate the working of the trim method with a simple example.
Example #1
Code:
class java_trim {
public static void main(String args[]) {
String line = " This is Java Trim Example with whitespaces ";
System.out.println(line); // without trim method
System.out.println(line.trim()); // with trim method
}
}
Output:
Code Interpretation: Here is our class java_trim; we have created the main class with a string variable name line, with a String with whitespaces at the beginning and the end. Then, we printed the string as it is, passed the trim method, and provided the output. The output is as expected, without any whitespaces. The above code will print two lines on proper compilation and execution, first with whitespaces and another without. Refer to the attached screenshot for output.
As you can see, there are whitespaces at the beginning of the string, and for the second line, they are omitted. Next, we’ll demonstrate another example with the trim() Function in Java, and we will now track the difference between the lengths of the string.
Example #2
Code:
class java_trim {
public static void main(String[] args) {
String line1 =" This is just another example of Java Trim1 ";
System.out.println(line1.length());
System.out.println(line1); //this is without trim method
String line2 = line1.trim();
System.out.println(line2.length());
System.out.println(line2); //this is with trim method
}
}
Output:
Code Interpretation: In our second demonstration program, we followed the same pattern as the previous one but used a different method to keep track of the string changes. We started with our class java_trim, then the main class within. Declared the first string with a string value that has to lead and trail whitespaces. Then we simply printed the string’s length to keep track of changes, and then the original string printed. Then, we have our second string, a trimmed version of the first string. Here, you can see the implementation of the trim method for the first string. Finally, we have printed the length of the edited string and then the edited string.
Here, you will notice a difference in the length count of both strings. Refer to the screenshot below for output.
Now that we have understood various ways to implement the trim() function in Java, let’s demonstrate a final example with String Array.
Example #3
Code:
public class java_trim1{
public static void main(String[] args) {
String[] values = { " java", "trim "};
for (String val : values) {
String trimmed = val.trim();
System.out.println("[" + val + "]");
System.out.println("[" + trimmed + "]\n");
}
}
}
Output:
Code Interpretation: In our final example, we have implemented the Trim method with a String Array. Code begins with Public class declaration java_trim1, then our main class. String[] declares an array of strings, followed by the variable name and the values within. Then, we have a for loop to check every value in the array. In the trim() Function in Java, for loop, pick every item in the array and apply the trim method. The trimmed value will be saved in another String variable named trimmed. Then, we have two simple print statements; the first statement will print the currently selected item from the array as it is. Ex. “[ java]” will be printed. Then, the edited version of the same item will be printed. “val” and” trimmed” have the presently selected items from an array; val has the string in original, while trimmed returns the edited string. Refer to the attached screenshot for the proper output.
Specifically, Trim does not have any particular use, but the best application can be a file to be read that might have multiple unwanted white spaces; the trim method can be used, and the file can be cleaned. For different programming languages, differently named methods are available for a similar operation; for Ruby or pearl, chop and chomp are used, and strip() is used with Python.
Example #4
Code:
//Java package
//package com.string.trim;
//creating class
public class JavaTrim {
// main method for run the Java application
public static void main(String args[]) {
// declaring a string
String string1 = " Hi, I am Paramesh ";
// displaying the output
System.out.println("String output after trimming :" + string1.trim());
// declaring a string
String string2 = " Hi, I am Amardeep ";
// displaying the output
System.out.println("String output after trimming :" + string2.trim());
}
}
Output:
Example #5
Code:
//Java package
//package com.string.trim;
import java.util.Scanner;
//creating class
public class JavaTrim {
// main method for run the Java application
public static void main(String args[]) {
Scanner scanner=new Scanner(System.in);
System.out.println("Please enter string with empty space starting and ending=>");
// Asking a user to enter input string
String string1 = scanner.nextLine();
// displaying the output
System.out.println("String output after trimming :" + string1.trim());
System.out.println("Please enter string with empty space starting and ending=>");
// Asking a user to enter input string
String string2 = scanner.nextLine();
// displaying the output
System.out.println("String output after trimming :" + string2.trim());
scanner.close();
}
}
Output:
Example #6
Code:
//Java package
//package com.string.trim;
import java.util.Scanner;
//creating class
public class JavaTrim {
// main method for run the Java application
public static void main(String args[]) {
Scanner scanner=new Scanner(System.in);
System.out.println("Please enter string with empty space starting and ending=>");
// Asking a user to enter input string
String string1 = scanner.nextLine();
System.out.println("String output before trimming: "+string1.trim());
// displaying the output
System.out.println("String output after trimming :" + string1.trim());
System.out.println("Please enter string with empty space starting and ending=>");
// Asking a user to enter input string
String string2 = scanner.nextLine();
System.out.println("String output before trimming: "+string2.trim());
// displaying the output
System.out.println("String output after trimming :" + string2.trim());
scanner.close();
}
}
Output:
Example #7
Code:
//Java package
//package com.string.trim;
import java.util.Scanner;
//creating class
public class JavaTrim {
// main method for run the Java application
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter string with empty space starting and ending=>");
// Asking a user to enter input string
String string1 = scanner.nextLine();
System.out.println(
"String output before trimming: " + string1.trim() + " and it's length is :" + string1.length());
// displaying the output
System.out.println(
"String output after trimming :" + string1.trim() + " and it's length is :" + string1.trim().length());
scanner.close();
}
}
Output:
Difference between trim() method and replaceAll() method
Aspect | trim() Method | replaceAll() Method |
Functionality | Removes leading and trailing whitespaces. | Can replace specified characters or patterns. |
Modification | Does not modify the original string. | Returns a new string with replacements. |
Character Set | Removes spaces, tabs, and newlines at the edges. | Replaces characters based on a regex pattern. |
Usage Example | java String trimmed = original.trim(); | java String replaced = original.replaceAll(“\\s”, “”); |
Scope | Limited to trimming whitespaces at edges. | Flexible for custom replacements and patterns. |
Performance | Typically, it is faster for simple whitespace removal. | Slightly slower, especially for complex regex patterns. |
Common Use Cases | Trimming user input dealing with formatted text. | Removing specific characters or patterns within strings. |
Best Practices for Using Trim () in Java
Following best practices when using the trim() method in Java is crucial to remove leading and trailing whitespaces from a string to ensure efficient and correct usage.:
- Null Check: Always check for null before applying trim() to avoid NullPointerException.
- Immutable Strings: Remember that trim() returns a new string, and the original string remains unchanged. Assign the result back to the variable if needed.
- Understand Whitespace: Trim() removes standard whitespace characters (spaces, tabs, and line breaks) but not other non-printable characters.
- Custom Trimming: If you need to remove custom characters, consider using regular expressions or other methods for more flexibility.
- Performance Considerations: If you perform trimming operations in a loop or on many strings, consider the performance impact. A custom trimming solution might be more efficient without creating unnecessary string objects.
- Consistent Code Style: Maintain a consistent code style throughout your project when using trim(). This includes deciding whether to trim in place or create a new variable and whether to check for null before trimming.
Conclusion
Java’s trim() function efficiently removes leading and trailing whitespaces from strings. Developers should be mindful of null checks, immutability, and whitespace understanding and consider custom trimming for specific requirements. Consistent coding practices ensure proper usage of this method in Java applications.
Recommended Articles
We hope this EDUCBA information on “trim() Function in Java” benefited you. You can view EDUCBA’s recommended articles for more information.