How to Use Java String Class trim() Method

Function Description

Java String class trim() method is used to remove the white space from the beginning and end of the string.

If String does not have any leading or trailing whitespaces it does not do anything and return the same string.

For example: If the string value is ” test “. It has leading and trailing white space. If we apply the trim() method on this string it will remove the white spaces from the beginning and end of the string and return the value “test”.

String str = ” test “;

System.out.println(str.trim());

Many times we see while comparing two strings, it returns false while the content of both the strings is the same. This issue comes because of leading or trailing whitespaces in the string. Even while we print the string on the console to check the issue it is untouched to figure out. But If we do a comparison after applying the trim() method we found the required result.

Method Signature

public String trim()

Parameter(s)

None

Return Type

It returns a string. If string has leading or trailing or trailing both whitespaces, it returns string after removing leading and trailing whitespaces. If the string does not have leading or trailing white space, it returns as it is.

Example of Java String Class trim() Method

public class ExampleStringTrim {

    public static void main(String[] args) {

          // creating string object leading with white space

          String strWithWhiteSpace = "  Welcome to String trim Function learning ";

          System.out.println("String before removing white spaces : '" + strWithWhiteSpace + "'");

          // return string after removing the starting and ending white spaces from

          String strAfterRemovingWhiteSpace = strWithWhiteSpace.trim();

          System.out.println("String after removing white spaces : '" + strAfterRemovingWhiteSpace + "'");
 
          // creating string object without white space

          String strWithoutWhiteSpace = "Welcome to String trim Function learning";
 
          // comparing string with space and without space

          boolean areStringsEqual = strWithWhiteSpace.equals(strWithoutWhiteSpace);

          System.out.println("Comparing both strings equality without trim() method : " + areStringsEqual);
 
          // comparing two string with space and without space

          areStringsEqual = strWithWhiteSpace.trim().equals(strWithoutWhiteSpace.trim());

          System.out.println("Comparing both strings equality with trim() method : " + areStringsEqual);
 
    }

}
 

Output:
 
String before removing white spaces : '  Welcome to String trim Function learning '

String after removing white spaces : 'Welcome to String trim Function learning'

Comparing both strings equality without trim() method : false

Comparing both strings equality with trim() method : true

Other Methods of String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2int length()Returns the number of characters count  in  a string.
3static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
4static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
5String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
6String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
7boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
8static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
10boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
11boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
12String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
13String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
14String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
15String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
16String replaceFirst(String regex, String replacement)Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression.
17static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
18String[] split(String regex)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. String is breaked into strings from all  the matching regular expressions.
19String[] split(String regex, int limit)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit.
20String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
21int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
22int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
23int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
24int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
25int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
26int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
27int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
28int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
29String toLowerCase()Returns all the characters of the string in lowercase .
30String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
31String toUpperCase()Returns all the characters of the string in uppercase.
32String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
33static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

In this article, we learned all about the trim() method of String class with examples. Apart from the trim() method, we got an idea about other String methods too. We will come up with more articles explaining other String methods with examples. For more details please click on the respective methods link.

This article was written by Renu Singh

14+ Years of experience in various phases of the software development life cycle. Specialties: Java/J2EE, Struts, Hibernate, JSF, JSP, Servlets, AJAX, Oracle, Oracle Knowledge, SQL Server 2000, DB2, EJB3.0. Companies Worked For: 1) Tata Consultancy Services 2) Infogain 3) TS Infotech 4) Daffodil Software Ltd.

Leave a Reply

Your email address will not be published. Required fields are marked *