My IDE is marking the following code snippet's second function call as a potential source for a NullPointerException, and I'm unsure if that is actually the case.
The snippet:
Sprite tmp = coordinateUtils.getSpriteUnderEntity(p);
if( isOutOfBounds(p)
||(p.collides(tmp)&&Resource.isImpenetrable(tmp.getType()))
){
//do stuff
}
(For clarification coordinateUtils.getSpriteUnderEntity()
takes a Sprite
as argument for its coordinates then returns the (background) Sprite
currently under it, or null
if the Sprite
has nothing under it)
p
is a projectile which is a kind of Sprite
, which has a collides
method while tmp
is a Sprite. Here's a simplified version of that method (simplified as in the actual collision logic will be hidden as it's irrelevant for this question).
public boolean collides(Sprite other){
return other != null && doesItCollide(other);
}
other
(tmp
in the snippet) is in fact nullable but since collides
is called before getType()
, and that would return false if other
(tmp
) was null
I can't ever run into a NullPointerException
here, right?
To rephrase the question, java's evaluation is lazy here, right?
public boolean collides(Sprite other){
return other != null && doesItCollide(other);
}
No it won't be evaluated. Java &&
operator “short-circuits”, that means it evaluates the left expression first and only if it is true
, evaluates the right one. It is possible that the IDE is not “smart enough” to figure such cases.
Different thing is that the method can be marked as throwing the NPE. In this case, you must (or you should) handle it, because it does not have to be caused by the argument, but by something inside the method.
See also this answer.