The Java compareTo()
method compares the given string lexicographically (an order similar to the one used in a dictionary) with the current string on the basis of the Unicode value of each character in the strings.
This method returns an integer upon its implementation.
The Java lexicographic order is as follows:
There are three cases when the compareTo()
method is used.
The method returns if the two strings are equivalent:
class MyClass {public static void main( String args[] ) {String str1="abcd";String str2="abcd";System.out.println(str1.compareTo(str2));}}
The method returns a negative number when the string calling the method lexicographically comes first:
class MyClass {public static void main( String args[] ) {String str1="abCd";String str2="abcd";System.out.println(str1.compareTo(str2));}}
The method returns a positive number when the parameter passed in the method lexicographically comes first:
class MyClass {public static void main( String args[] ) {String str1="abcd";String str2="abCd";System.out.println(str1.compareTo(str2));}}
This number represents the difference between the Unicode values of the string passed as the input parameter (str2
) and the string (str1
) calling the method.
result= Unicode of str1 - Unicode of str2
Free Resources