Java String compareTo()
The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0.
It compares strings on the basis of the Unicode value of each character in the strings.
If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0.
Syntax
The method accepts a parameter of type String that is to be compared with the current string.
It returns an integer value. It throws the following two exceptions:
ClassCastException: If this object cannot get compared with the specified object.
NullPointerException: If the specified object is null.
Internal implementation
Java String compareTo() Method Example
FileName: CompareToExample.java
Output:
0 -5 -1 2
Java String compareTo(): empty string
When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios:
- If first string is an empty string, the method returns a negative
- If second string is an empty string, the method returns a positive number that is the length of the first string.
FileName: CompareToExample2.java
Output:
5 -2
Java String compareTo(): case sensitive
To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence.
Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters.
FileName: CompareToExample3.java
Output:
-32
Conclusion: It is obvious by looking at the output that the outcome is not equal to zero. Hence, the compareTo() method takes care of the case sensitiveness of characters.
Java String compareTo(): ClassCastException
The ClassCastException is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal (“Sehwag”).
FileName: CompareToExample4.java
Output:
Exception in thread "main" java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable
Java String compareTo(): NullPointerException
The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example.
FileName: CompareToExample5.java
Output:
Exception in thread "main" java.lang.NullPointerException at CompareToExample5.main(CompareToExample5.java:9)