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

Jason Rogers picture Jason Rogers · Dec 15, 2010 · Viewed 54.9k times · Source

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

Asaph picture Asaph · Dec 15, 2010

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.