Q:

Java compareTo step by step execution

I have basic understanding that Java compareTo method lexicographically compares two strings.
I have read basics here String Comparison in Java
I have following example:
public class CompareTo {
   public static void main(String args[]) {
       String str1 = "String";
       String str2 = "compareTo";
       String str3 = "String";
       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);
   }
}

I get var1 = -16 and var2 = 0.
If someone explains me this Lexicographic comparison step by step It would be of great help.
Thanks.

A:

Well, if you print :
System.out.println ('S'-'c');

you get -16
String's compareTo compares the two Strings one character at a time. The first pair of characters that are not equal (in your case 'S' of "String" and 'c' of "compareTo") determines the result. Since lexicographically 'S' comes before 'c', the comparison returns a negative value, which means "String" should come before "compareTo".
In your second comparison, all pairs of characters are equal, so compareTo returns 0.

