Can anybody help me on following issue:
I have code like:
if(cond1 && cond2 && .. && cond10)
Here, cond1 are expensive operations whose output is Boolean.
Now my question is what JAVAC will do, when cond2 output is false. Specifically, is it goes evaluate cond3 's output or stops evaluation ?
More illustratively,
if(cond1 && cond2 && .. && cond10)
//do this
and
if(cond1){
if(cond2){
.
.
.
if(cond10){
//do this
}
are same in java (in case of execution way) ?
The &&
operator always short-circuits on false
. Condition 3 will only be evaluated if conditions 1 and 2 are true
.
If the entire expression is &&
or ||
then Java will use short-circuit evaluation. That means if everything is &&
it will stop after the first false and if everything is ||
it will stop after the first true.
Yes your code snippets are equivalent. The logic AND operator is in Java short-circuit.
Java will exit that check as soon as it finds out that one of the values is false.
Likewise, it'll do what you expect with OR as soon as it finds out that one of the values is true.
No need to evaluate the others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With