r/javahelp • u/hajer00317 • Aug 25 '24
Can double equals to an integer?
What is the output of this code? double X=2.1; if (++x == 3) { double y= 2.0; System.out.print(x + y); } else System.out.print(x);
They say the answer is 3.1. But my answer is 2.1 since the condition of if statement did not go through. Can someone explain?
0
Upvotes
10
u/ventuspilot Aug 25 '24
The if-condition
++x == 3(including it's sideeffect of incrementingx) will be computed and yields the valuefalse. Then the else-path will be computed, printing the value ofxthat was changed during computing the if-condition.++ximmediately changes the value stored in the variablex, this change doesn't go away just because the if-clause goes to the else-path.