public class AndOperator {
public static void main(String[] arg) {
int value = 8;
int count = 10;
int limit = 11;
if (++value % 2 == 0 && ++count < limit) {
System.out.println("here");
System.out.println(value);
System.out.println(count);
} else{
System.out.println("there");
System.out.println(value);
System.out.println(count);
}
}
}
i am getting output as
there
9
10
explain how count is 10....?
&&
is short-circuit operator. It will only evaluate the 2nd expression if the 1st expression evaluates to true.
Since ++value % 2 == 0
is false, hence it doesn't evaluate the 2nd expression, and thus doesn't increment count
.
++value
= 9 so ++value % 2 == 0
is false
so ++count < limit
is not evaluated.
This is called Short circuit evaluation. See the wikipedia page : http://en.wikipedia.org/wiki/Short-circuit_evaluation
Since you are using &&
(logical and) operator.
logical and evaluate second condition only if first condition is evaluated to true
Here in your code first condition ++value % 2 == 0
is evaluated to false
,so second condition ++count < limit
won't be evaluated.
If you want to execute ++count < limit
also use &
.
more information read Difference between & and &&
Because ++value % 2 == 0 is false, thus it won't return the first statement. The reason ++value % 2 is false is because value is incremented by one before the mod operator is evaluated. So ++value % 2 is 9 % 2 which != 0.
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