Checking all conditions in a logical disjunction

2019-08-03 18:33发布

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.

4条回答
倾城 Initia
2楼-- · 2019-08-03 19:00

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 |.

查看更多
放我归山
3楼-- · 2019-08-03 19:08

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

查看更多
Bombasti
4楼-- · 2019-08-03 19:09

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.

查看更多
【Aperson】
5楼-- · 2019-08-03 19:18

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 ||.

查看更多
登录 后发表回答