Generally, is there a difference between
if("x".equalsIgnoreCase(myStrVar))
and
if(myStrVar.equalsIgnoreCase("x"))
in that the first will not cause a null pointer exception, but the second one will if in both scenarios myStrVar is null?
Generally, is there a difference between
if("x".equalsIgnoreCase(myStrVar))
and
if(myStrVar.equalsIgnoreCase("x"))
in that the first will not cause a null pointer exception, but the second one will if in both scenarios myStrVar is null?
Yes, that's correct. However, that doesn't mean you should always use the former ("safe") version.
If you are absolutely confident that myStrVal is non-null - meaning that for it to be null would indicate a bug - I would probably use the second form.
if (x == 0) rather than if (0 == x)So:
myStrVal being null, then perform a check for that firstmyStrVal being null in the same way as any other non-"x" value, use the first formmyStrVal being null as a bug, use the second formIf I got your question right, the answer is "yes". :)
Exactly, because the implementation is
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true :
(anotherString != null) && (anotherString.count == count) &&
regionMatches(true, 0, anotherString, 0, count);
}
This is a nice instance of the (Yoda Conditions-)rule: "you should start with the constant to avoid nullpointer dereferences".