Java String compareToIgnoreCase method

Signature: public int compareToIgnoreCase(String str) 
Sample usage: strone.compareToIgnoreCase(strtwo),


How  compareToIgnoreCase method works

Compares two strings lexicographically ignoring character case differences between them.The case normalization of all characters in both strings is by calling  Character.toLowerCase(Character.toUpperCase(character)) on each character.

The result is a negative int if this string lexicographically precedes the argument string e.g if strone precedes strtwo  when all characters in both strings are in lower case or “thisString” (as “thisstring”) precedes “anotherString”(as “anotherstring”).


The result is a positive int if the argument string lexicographically precedes this string e.g if strtwo precedes strone  when all characters in both strings are in lower case or  “anotherString”(as “anotherstring”) precedes “thisString” (as “thisstring”).


The result is zero (0) if both strings are equal  when all characters in both strings are in lower case.

If one string is a substring of the other string,the difference in length of both strings is returned with the length being a negative int if this string’s(e.g strone)length  is less than the argument string’s(e.g strtwo) length or a positive int when the argument string’s(e.g strtwo)length is less than this string’s(e.g strone)length.


Example 1

String strone=“java”;

String strtwo=“Java”;

The invocation strone.compareToIgnoreCase(strtwo) returns 0 .

The two strings are equal in length and character composition(including case when converted to lowercase) from first to last index so we return 0.


Example 2

String strone=“Cheerleader”;

String strtwo=“cheer”;

The invocation strone.compareToIgnoreCase(strtwo) returns 6


The character ‘C’ in Cheerleader will be converted to lowercase ‘c’ hence we end up comparing ‘cheerleader’ and ‘cheer’ .As the case with the compareTo,this returns the difference in length of strone and strtwo,11-5=6,since the shorter string is a substring of the longer string. If it were  strone.compareTo(strtwo),-32 would have been returned as discussed here.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.