Why is this an issue?
Using toLowerCase()
or toUpperCase()
to make case insensitive comparisons is inefficient because it requires the creation
of temporary, intermediate String
objects.
Noncompliant code example
private void compareStrings(String foo, String bar){
boolean result1 = foo.toUpperCase().equals(bar); // Noncompliant
boolean result2 = foo.equals(bar.toUpperCase()); // Noncompliant
boolean result3 = foo.toLowerCase().equals(bar.toLowerCase()); // Noncompliant
}
Compliant solution
private void compareStrings(String foo, String bar){
boolean result1 = foo.equalsIgnoreCase(bar); // Compliant
}
Exceptions
No issue will be raised when a locale is specified because the result could be different from equalsIgnoreCase()
. (e.g.: using the
Turkish locale)
private void compareStrings(String foo, String bar, java.util.Locale locale){
boolean result1 = foo.toUpperCase(locale).equals(bar); // Compliant
}