Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Jason Rogers Avatar asked Dec 15 '10 04:12

Jason Rogers


People also ask

Is equalsIgnoreCase case sensitive?

Clearly, the difference between equals and equalsIgnoreCase in Java is case-sensitity while performing the string comparisons. equals() method does case-sensitive comparison. equalsIgnoreCase() method does case-insensitive comparison.

What is the purpose of using equalsIgnoreCase () in string Program?

Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

What is the difference between equals () and equalsIgnoreCase () in string functions?

Difference between equals() vs equalsIgnoreCase() in JavaUse equals() in Java to check for equality between two strings. Use equalsIgnoreCase() in Java to check for equality between two strings ignoring the case.

How can we convert a string to uppercase and lowercase in Java?

Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.


2 Answers

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.

like image 139
Asaph Avatar answered Sep 17 '22 18:09

Asaph


equalsIgnoreCase avoids problems regarding Locale-specific differences (e.g. in Turkish Locale there are two different uppercase "i" letters). On the other hand, Maps only use the equals() method.

like image 39
koljaTM Avatar answered Sep 21 '22 18:09

koljaTM