Reputation: 23443
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?
Upvotes: 1
Views: 399
Reputation: 1500065
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 formUpvotes: 7
Reputation: 7447
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".
Upvotes: 1
Reputation: 12519
Obviously a NullPointerException
will be raised in the second scenario if myStrVar == null
. You can't call equalsIgnoreCase(String str)
on null
but you can pass in null
as an argument.
Upvotes: 1
Reputation: 500247
Your statement that the second version would cause a NullPointerException
, whereas the first one wouldn't, is correct.
Upvotes: 1