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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With