How do I make my string comparison case-insensitive?

The best way is to use str.equalsIgnoreCase("foo"). It’s optimized specifically for this purpose.

You can also convert both strings to upper- or lowercase before comparing them with equals. This is a trick that’s useful to remember for other languages which might not have an equivalent of equalsIgnoreCase.

str.toUpperCase().equals(str2.toUpperCase())

If you are using a non-Roman alphabet, take note of this part of the JavaDoc of equalsIgnoreCase which says

Note that this method does not take locale into account, and will
result in unsatisfactory results for certain locales
. The Collator
class provides locale-sensitive comparison.

Leave a Comment