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. SyntaxThe 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 implementationJava String compareTo() Method ExampleFileName: CompareToExample.java Test it NowOutput: 0 -5 -1 2 Java String compareTo(): empty stringWhen 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:
FileName: CompareToExample2.java Test it NowOutput: 5 -2 Java String compareTo(): case sensitiveTo 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(): ClassCastExceptionThe 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(): NullPointerExceptionThe 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) Next TopicJava String concat() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India