OverFlower OverFlower - 1 month ago 7
Java Question

The compareToIgnoreCase method in Java

I found this piece of code on the internet and I'm trying to understand it...I don't know why the output is:
10
-10
-69

String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
String str4 = "Strings are immutabl ";

result = str2.compareToIgnoreCase( str3 );
System.out.println(result);

result = str3.compareToIgnoreCase( str1 );
System.out.println(result);

result = str4.compareToIgnoreCase( str2 );
System.out.println(result);

Answer

Comparisons are similar to the ordering that one might find in a dictionary.

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.

More specifically, the method provides the first non-zero difference in ASCII values.

Thus "computer".compareTo ("comparison") will return a value of (int) 'u' - (int) 'a' (21). Since this is a positive result, the parameter ("comparison") is lexicographically first.

For your example:

result = str4.compareToIgnoreCase( str2 );

will return -69 because in ASCII Decimal SPACE has the value 32 and 'e' has the value 101. If you compare str4 with str2, the only difference is the last character ' ' for str4 and 'e' for str2. So you calculate (int) 'SPACE' 32 - (int) 'e' 101 = -69. Since the rest of these two strings are equals, it's 0 + (-69) = -69.