Small doubt. Why is the output of the following code 1
? Why not 3
?
int i = 0;
boolean t = true, f = false, b;
b = (t && ((i++) == 0));
b = (f && ((i+=2) > 0));
System.out.println(i);
the Conditional-And operator - &&
- is short circuit. It doesn't evaluate the right operand if the left operand is false. That's why ((i+=2) > 0)
is never evaluated, and i
remains 1.
From the JLS 15.23:
The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
Here is the case
b = (f && ((i+=2) > 0)); // here f is false
Now false && anything
is false
. &&
is short circuit operator so it will not evaluate ((i+=2)
part since left one is false
. So i
will remain 1
Just try to change
b = (f && ((i+=2) > 0));
To
b = (f & ((i+=2) > 0));// non short circuit
Now you will get 3
.
That is the two different behavior of short circuit
and non short circuit
AND
.
For more info.
Agree with the posted answer as &&
is responsible for this.
You should note here that your statement b = (t && ((i++) == 0));
is equivalent to
if(t){
if(i++==0){
b=true;
}
}
and second statement b = (f && ((i+=2) > 0));
is equivalent to,
if(f==true){
i=i+2;
if(i>0){
b=true;
}
}
For example:
if(p && q){
// do something
}
if p
is evaluated to be false, the rest of the statement need not be evaluated because of the very definition of &&
(p
AND q
must be true). If p
is not true, then the statement cannot possibly be true.