What is String.compareToIgnoreCase() in Java?

We can use the compareToIgnoreCase() method to compare two strings lexicographicallyin their dictionary order which ignores casei.e., lower case a is equal to uppercase A.

Syntax

strObj1.compareToIgnoreCase(strObj2);

This method returns:

  • 0 if both strObj1 and strObj2 are equal.
  • a negative integer if strObj1 comes before the strObj2.
  • a positive integer if strObj2 comes before the strObj1.

Code

class CompareString {
public static void main( String args[] ) {
String apple = "apple";
String ball = "ball";
String appleInUpperCase = "APPLE";
String ballInUpperCase = "BALL";
System.out.println("apple.compareToIgnoreCase(APPLE)");
System.out.println(apple.compareToIgnoreCase(appleInUpperCase) );
System.out.println("\nball.compareToIgnoreCase(BALL)");
System.out.println(ball.compareToIgnoreCase(ballInUpperCase) );
System.out.println("\napple.compareToIgnoreCase(ball) -- apple comes before ball so we will get -ve number" );
System.out.println(apple.compareToIgnoreCase(ball) );
System.out.println("\nball.compareToIgnoreCase(apple) -- ball comes after apple so we will get +ve number");
System.out.println(ball.compareToIgnoreCase(apple) );
}
}

Explanation

In the above code, we created four strings:

  • apple
  • APPLE
  • ball
  • BALL

We tried to compare strings in different combinations with the compareToIgnoreCase method.

First, we compared:

"apple".compareToIgnoreCase("APPLE");

When we use compareToIgnoreCase to compare the strings, the case of the strings is not considered. apple is equal to APPLE. The compareToIgnoreCase method will return zero if the two strings are equal, irrespective of the case.

This also applies to the comparison of:

"ball".compareToIgnoreCase("BALL");

Then we compared:

"apple".compareToIgnoreCase("ball");

apple comes before ball, so the compareToIgnoreCase method will return a negative number.

Then we compared:

"ball".compareToIgnoreCase("apple");

ball comes after apple, so the compareToIgnoreCase method will return a positive number.

Free Resources