Jason Rogers Jason Rogers - 1 month ago 14
Java Question

Java: String: equalsIgnoreCase vs switching everything to Upper/Lower Case

It came to my attention that there a several ways to compare strings in Java.

I just got in the habit ages ago to use

equalsIgnoreCase
to avoid having problems with case sensitive strings.

Others on the other hand prefer passing everything in upper or lower case.

From where I stand (even if technically I'm sitting), I don't see a real difference.

Does anybody know if one practice is better than the other? And if so why?

Answer

Use equalsIgnoreCase because it's more readable than converting both Strings to uppercase before a comparison. Readability trumps micro-optimization.

What's more readable?

if (myString.toUpperCase().equals(myOtherString.toUpperCase())) {

or

if (myString.equalsIgnoreCase(myOtherString)) {

I think we can all agree that equalsIgnoreCase is more readable.