compareToIgnoreCase() String Example


java.lang.String class comes with many methods to check two strings contain same characters in the same sequence. To do this, String class comes with equals(), compareTo(), equalsIgnoreCase() and compareToIgnoreCase() methods. This is tutorial is on compareToIgnoreCase() String.

We have seen earlier compareTo() method which does case-sensitive comparison lexicographically. Now we discuss compareToIgnoreCase() method which does the same job but with ignoring the case of letters. compareTo() and compareToIgnoreCase() methods differ in the same way as equals() and equalsIgnoreCase() methods.

Following is the method signature of compareToIgnoreCase() String as defined in Java API.
  • public int compareToIgnoreCase(String anotherString): Compares two strings lexicographically without considering the case of the characters. Character by character of both strings, with case-insensitivity, is compared. If the ASCII values of both characters is same, then the method returns 0 else some integer value of the difference of ASCII values. Note, equalsIgnoreCase() method returns boolean value. Introduced with JDK 1.2.

Following example illustrates the usage of the above method.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "ABCD";
  String str2 = "abcd";
  String str3 = "ABKD";
  
  int x = str1.compareToIgnoreCase(str2);
  int y = str1.compareToIgnoreCase(str3);

  System.out.println("integer value when two strings "+ str1 + " and " + str2 + " are same: " + x);
  System.out.println("integer value when two strings "+ str1 + " and " + str3 + " are not same: " + y);
 }
}


compareToIgnoreCase() String
Output screen of compareToIgnoreCase() String Example

  1. When "ABCD" and "abcd" are same but for case of characters, the method returned 0.
  2. When "ABCD" and "ABKD" are not same, the method returned, the difference of C and K letters ASCII value -8.

What is lexicographical comparison?

Character by character of each string is compared. That is, the method takes characters, one-by-one, of both strings and compares. When both characters are same, the method returns 0 (the difference of their ASCII values). When dissimilar characters are compared and thereby when the difference is non-zero, further comparison is stopped and the difference is returned. This is known as lexicographical comparison (character-by-character comparison).

Leave a Comment

Your email address will not be published.