Are both the String comparison methods below considered to be equal
public class TestString {
public static final String CONSTVAL="foo";
public boolean testString1(String testVal) {
return testVal.equalsIgnoreCase(CONSTVAL);
}
public boolean testString2(String testVal) {
return CONSTVAL.equalsIgnoreCase(testVal);
}
}
or should one type of comparison be favoured over another?
You should call equals on the constant since it avoids the risk of NullPointerException when testVal
is null.
public boolean testString2(String testVal) {
return CONSTVAL.equalsIgnoreCase(testVal);
}
One advantage of the latter is that it won't throw an exception if testVal
is null.
I would expect the results to be the same, other than that.
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