Java String compareToIgnoreCase() Method
Last Updated :
24 Dec, 2024
In Java, the String compareToIgnoreCase() method compares two Strings lexicographically means in dictionary order by ignoring the case differences. It evaluates the Unicode values of characters sequentially.
Example 1: Here, we will use the compareToIgnoreCase() method to compare strings that are lexicographically smaller, greater, or the same.
Java
class Geeks {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Python";
String s3 = "java";
// Compare strings lexicographically
System.out.println("" + s1.compareToIgnoreCase(s2));
System.out.println("" + s2.compareToIgnoreCase(s1));
System.out.println("" + s1.compareToIgnoreCase(s3));
}
}
Explanation: In the above example, "Java" comes before "Python" lexicographically, so the result is negative. "Python" comes after "Java", so the result is positive. "Java" is equal to "java" when ignoring case, so the result is zero.
Syntax of compareToIgnoreCase() Method
int compareToIgnoreCase(String s1)
Parameter: s1: The string to compare with the current string by ignoring the case differences.
Return Value: Based on the lexicographical order, this method returns an integer value
- If both strings are equal (case-insensitive), it returns 0.
- If the current string is lexicographically greater, it returns a positive number.
- If the current string is lexicographically smaller, it returns a negative number.
Example 2: Here, we will use the compareToIgnoreCase() to check if two strings are equal, ignoring case differences.
Java
class Geeks {
public static void main(String[] args) {
String s1 = "JAVA";
String s2 = "java";
// Check equality ignoring case
if (s1.compareToIgnoreCase(s2) == 0) {
System.out.println("The strings are equal (case-insensitive).");
} else {
System.out.println("The strings are not equal.");
}
}
}
OutputThe strings are equal (case-insensitive).
Explanation: In the above example, the method returns 0 if the strings are equal when ignoring case.
Example 3: Here, the compareToIgnoreCase() method throws a NullPointerException if the string which is compared is null.
Java
// Handle NullPointerException
// using compareToIgnoreCase()
class Geeks {
public static void main(String[] args) {
String s1 = "Java";
String s2 = null;
try {
// string comparison
System.out.println(s1.compareToIgnoreCase(s2));
} catch (NullPointerException e) {
System.out.println("Cannot compare to a null string.");
}
}
}
OutputCannot compare to a null string.