Checking all conditions in a logical disjunction

2019-08-03 18:47发布

问题:

I found the question in this line of code. Ignore the fact that this code does not make sense:

if (object != null || object.someMethod()) object.doSomething();

First I was thinking that this code will throw NullPointerException if object is null. But, this is a logical disjunction and if one of the conditions is true the whole condition is true. So the compiler doesn't checks the second condition and doesn't throws NullPointerException.

Is this Java Standard behavior or implementation specific? If the second case is true than this code is not secure.

回答1:

When object is not null, short-circuit evaluation occurs, and object.someMethod() is never called.

When object is null, this expression should throw a NullPointerException when object.someMethod() is evaluated.

This is not a particularly useful condition. Consider whether && was intended instead of ||.



回答2:

the || is defined by Java to be a short-circuit operator. So if the first condition is true it does not evaluate the second condition. This is distinct from the | operator which is NOT short-circuit. The reliance on short-circuit operators is VERY common practice when coding Java.

That said, Marco's comment is totally correct. You are using the || operator where you should probably be using the && operator. Same short-circuit rules apply.



回答3:

It is Java standard behaviour. Logical OR (||) is a "short-circuit" operator meaning it only evaluates what it needs to, to determine whether the entire condition is true or not. If you want to force evaluation of each guard use |.



回答4:

someMethod could be a static method that returns true even though the object does not exist. Compiler should warn you.