r/javahelp • • 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

13 comments sorted by

View all comments

10

u/ventuspilot Aug 25 '24

The if-condition ++x == 3 (including it's sideeffect of incrementing x) will be computed and yields the value false. Then the else-path will be computed, printing the value of x that was changed during computing the if-condition.

++x immediately changes the value stored in the variable x, this change doesn't go away just because the if-clause goes to the else-path.

3

u/xenomachina Aug 25 '24

Adding to this excellent answer: as for the question in your title, OP, the answer is "yes, a double can equal an int".

2.0 == 2
3.0 == 3
3.1 != <any int>

However, that is not what's happening in you code snippet.

++x immediately changes the value stored in the variable x, this change doesn't go away just because the if-clause goes to the else-path.

Incidentally, this is one of the reasons many people consider it to be bad style to use a side-effect-causing operator, like ++, in the middle of a larger expression. It's easy to miss that a side-effect (incrementing the variable, in this case) is happening inside of a larger expression (the condition, in this case). It's also pretty easy to confuse ++x with x++.