Understanding the Java String Trim Method

java string trimStrings are one of the most extensively used objects in Java. Some languages like C, C++ treat them as an array of characters while in Java, String is a special class encapsulated in ‘java.lang’ package, which is imported automatically in each Java program. The String class is special, because in Java it is designed with features of both primitives and object types. Due to the importance of strings, it is integral to learn basics of the string comparison, searching and other string manipulation methods. One of the most important methods of the Java String class is the Java String Trim method.

Want to learn more about Java? Take a course at Udemy.com.

What is Java String Trim Method?

The Java String Trim method is an instance method that is use to remove extra spaces from the start and end of a string. The String Trim method is used on the string object or literal. In Java, Strings are immutable, so once they are created, the content cannot be modified. Due to this reason, the result will be a newly created string object with no spaces at both ends of a string. The definition of ‘trim’ method in String class looks like this:

String trim ()

From the above definition of the ‘trim’ method, it is evident that after trimming the string, it returns a new string object. When there is no space to trim at both sides, the same object of type String will be returned instead of a new one.

How Java String Trim Method works?

The following code snippet demonstrates how a ‘trim’ is performs on string literal.

Code snippet:

System.out.print ( "Input: " );

System.out.println ( "  Remove extra spaces from this string literal   " );

System.out.print ( "Output: " );

System.out.println ( ”  Remove extra spaces from this string literal   “.trim () );

Console output:

Input:      Remove extra spaces from this string literal      Output: Remove extra spaces from this string literal

In the above code snippet and its output, it is clear that the String ‘trim’ method removes the extra space from both sides of the string literal.

To use a Java String ‘trim’ method on string object it is called with that object like an instance method. Following code snippet demonstrates the use of ‘trim’ on string object.

Code snippet:

String sampleString= new String ( "     Remove extra spaces from this string object      " );

System.out.println ( "Input: " );

System.out.println ( sampleString );

System.out.println ( "Output: " );

String resultantString = sampleString.trim();

System.out.println ( resultantString );

Console Output:

Input:

Remove extra spaces from this string object

Output:

Remove extra spaces from this string object

In the above code snippet, if a string points to a ‘null’ value then this Java String ‘trim’ method will throws a ‘NullPointerException’ exception.

To learn Java for Android applications, take a course at Udemy.com. 

Java String Trim Method on Java Array:

The Java String ‘Trim’ method cannot be used on Java ‘Array’ directly. To remove the extra space from each element of array, ‘trim’ method have to be called on each element of array using loop to iterate through the elements of array. The following code snippet demonstrates the use of ‘trim’ method on an array.

Code snippet:

String[] sampleArray = new String[] {" This is a first element. ","  I am number 2.","Last one is me.   "};

for (int i = 0; i < sampleArray.length; i++) {

if (! sampleArray[i].trim ().equals ("") || sampleArray[i] != null)

sampleArray[i] =sampleArray[i].trim ();

}

In the above code snippet, each element of array is traversed using the ‘for’ loop. After a check of an empty string and ‘null’ value on each element of an array, the String ‘trim’ method is called on each element results in a new string object assign to a traversed element.

Java String Trim variant Apache LTrim and RTrim

In the Java String class, there is no variant of the ‘trim’ method but a third party ‘Apache’ provides a ‘StringUtils’ class with utility methods having left and right trim methods. Using these methods, you need an Apache library (jar) file included in your project.  The following is the definition of ‘ltrim’ and ‘rtrim’ method.

String ltrim (String stringToTrim, String patternToTrim, boolean ignoreCase)   

String rtrim (String stringToTrim, String patternToTrim, boolean ignoreCase)   

Unlike String ‘trim’ method Apache ‘ltrim’ and ‘rtrim’ have three parameters. The first one is the object of string that is to be trim. The second one is the chain to remove from string object and last one is a Boolean value which decides the operation is case insensitive or not. 

Java String Trim alternative ‘replaceAll’ method 

Using the String ‘trim’ method is easy to use with no flexibility. An alternative ‘replaceAll’ is a flexible choice to trim a string object not just from both sides but it can trim the string from either of its side. Following code snippets demonstrates the use of ‘replaceAll’ method to trim string from left, right and both sides.

Code snippet 1:

String sampleString= new String ( "     Remove spaces from left of a string object      " );

String resultantString = sampleString .replaceAll ("^\\s+","");

System.out.println ( resultantString );

Code snippet 2:

String sampleString= new String ( "     Remove spaces from right of a string object      " );

String resultantString = sampleString .replaceAll ("\\s+$","");

System.out.println ( resultantString ); 

Code snippet 3:

String sampleString= new String ( "     Remove spaces from both sides of a string object      " );

String resultantString = sampleString .replaceAll ("^\\s+|\\s+$","");

System.out.println ( resultantString );

Unlike the Java String trim method, ‘replaceAll’ is flexible enough to trim string from each side because ‘replaceAll’ uses the regular expression to perform an advance search on string and replace a match with the replacement string provides in a second argument.

In the above first code snippet the regular expression (^\\s+) is used to search all spaces at the start of the string. The ‘^’ symbol is a start of string followed by ‘\s+’ which is the extra space until a first character is encountered.

In a second code snippet, the regular expression (\s+$) is uses to search all the space from the last character present in a string. The ‘\s+’ all white spaces symbol of string is followed by the end of string symbol ‘$’.

The last code snippet has a combination of the regular expression use by first two examples concatenates with ‘|’ pipe symbol that’s why it trims the string from both end just like Java String trim method does.

For more interesting Java tutorials, take a course at Udemy.com.