My understanding is x++ == 0 runs first. But x is still -1 at the point of calculating (y = y++ / x) == 0? Otherwise it will be dividing by zero. I thought the output will be -5 but eclipse says 5. I’m going crazy.
public static void main(String[] args){
int x = -1;
int y = 5;
boolean s = (x++ == 0) && ((y = y++ / x) == 0);
System.out.println(x + y);
}
>Solution :
((y = y++ / x) == 0) is never evaluated since && is a short circuited logical AND operator, and (x++ == 0) is false, so s is evaluated to false without evaluating the second operand.
Hence, the output is
x + y
0 + 5 == 5
Note that if you change the && operator to &, which is not short circuited, the second operand will be evaluated, which will lead to division by 0 and ArithmeticException. x is incremented when the first operand is evaluated, so once the second operand is evaluated, x is already 0.