[Solved] The compareToIgnoreCase method in Java


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.

solved The compareToIgnoreCase method in Java