Search code examples
javacomparecompareto

What does the CompareTo function do in this situation in Java


public static void main(String[] args) {
     System.out.print("Comparing \"axe\" with \"dog\" produces ");
     // I don't understand what this does.
     int i = "axe".compareTo("dog");
     System.out.println(i);

     System.out.print("Comparing \"applebee's\" with \"apple\" produces ");
     // neither this.
     System.out.println( "applebee's".compareTo("apple") );


}

When i run the code it comes up with -3 and the next one is 5, I don't understand how you can compare letters and it coming up with numbers. The "applebee" and the "dog" are not even string variables This is for an assignment at school at this link


Solution

  • The Java String class provides the .compareTo () method in order to lexicographically compare Strings.

    The return of this method is an int which can be interpreted as follows:

    • returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
    • returns == 0 then the two strings are lexicographically equivalent
    • returns > 0 then the parameter passed to the compareTo method is lexicographically first.

    In your example:

    "axe".compareTo("dog") return -3 because axe is lexicographically come first in dictionary.

    It begins with first character of each string: a come before d in dictionary.if the compared characters are lexicographically equivalent it will go to the next characters in the string to compare them and so on.

     "applebee's".compareTo("apple") 
    

    The first 5 characters in first string "apple" is lexicographically equivalent to second string but characters bee's come after the second string so it will return 5 which is bigger than 0 because second string come first in dictionary.