Are these comparisons always safe from creating a NullPointer Exception ?
if( myObject == null || myObject.someMethod() == someValue )
{
if( myObject == null && myObject.getAlwaysTrue() )
{
}
}
Is there some directional precedence in java for condition evaluation, apart from short circuiting ?
UPDATE: I Know myObject.anything() will throw a NullPointer. Its just that I have come across such code by other programmers, and I want to know if there’s a safe way of squeezing multiple checks along with a null check in a single condition. I’m looking for a good rule to stick to.
No, this line is not safe:
If you know that
myObjectis null then you shouldn’t try to dereference it. If however you wrote this:Then it would be safe. This is because
&&(and||for that matter) has short-circuit evaluation. If you writea && band the expressionaevaluates to false, then the expressionbis not evaluated so it will not throw an exception. The left operand is always evaluated first.