What is String.compareToIgnoreCase() in Java?
We can use the compareToIgnoreCase() method to compare two strings a is equal to uppercase A
Syntax
strObj1.compareToIgnoreCase(strObj2);
This method returns:
- 0 if both
strObj1andstrObj2are equal. - a negative integer if
strObj1comes before thestrObj2. - a positive integer if
strObj2comes before thestrObj1.
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:
appleAPPLEballBALL
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.