We can use the compareToIgnoreCase()
method to compare two strings a
is equal to uppercase A
strObj1.compareToIgnoreCase(strObj2);
This method returns:
strObj1
and strObj2
are equal.strObj1
comes before the strObj2
.strObj2
comes before the strObj1
.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) );}}
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.