Condition evaluation process in Java [duplicate]

妖精的绣舞 提交于 2019-12-01 03:08:40

It should be always be left to right except the assignment operator = . You are using short circuit OR operator , hence if the first condition is true , rest of them won't be evaluated.

JLS 15.24:

The conditional-or operator is syntactically left-associative (it groups left-to-right).

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

From the JLS

At run time, the left-hand operand expression is evaluated first [...] If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

Aniket Thakur
if ( myList == null || myList.isEmpty() || xomeX == someY )

Yes the evaluation is from left to right!

and

If the first condition is true next condition is not evaluated. This concept is called Short-circuit evaluation. You can read more on this here. Similar SO question posted earlier is Java logical operator short-circuiting

1) left to right

2) in this case, if one condition is true, it doesn't evaluate the rest. so if myList is null, it won't throw a NullPointerException evaluating myList.isEmpty() (because it won't evaluate it)

Every operator has its own precedence and associativity.

These links are enough to answer your question.

|| is the short-circuit OR operator, that means that conditions are strictly evaluated from left to right, and this checking process stops on first true result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!