Reputation: 1245
Assume a scenario such as this;
if(event.getAdapter() != null && event.getAdapter().getCount() > 0)
In the code above, first i check if it is null then i check if count whether above zero. If first condition is checked before second condition then this code will work as intended. But if (i heard that jvm sometimes starts checking most failure conditions to speed up) second condition is checked than first one then this code will give runtime error.
So my question is, is above check code safe? Will it work as intended? or jvm may start from second condition sometimes?
Upvotes: 1
Views: 92
Reputation: 5123
When you use &&, all conditions will be executed from the left to the right until one of your conditions is evaluated as false.
example :
A && B && C
if B is false, C will not be evaluated.
However if you use just one &, all your conditions will be evaluated, even if one is false. It is the main difference between & and && as logical operator.
I hope it will help you.
Upvotes: 0
Reputation: 109532
Entirely safe, when a second thread cannot change the adapter.
Java 8 might yield an Optional<Adapter>
and allow a different formulation.
Upvotes: 4
Reputation: 201399
The above code is safe. The JVM will short-circuit the second evaluation if the first is false
.
The JLS-15.23. Conditional-And Operator &&
says (in part)
The conditional-and operator
&&
is like&
(§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand istrue
.
Upvotes: 2