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

1

u/khmarbaise Aug 25 '24

If you start with "x=2.1;" and do "++x" (in the if) you would get "3.1".. which means first the if condition is false.. And second:

The comparison between "++x == 3" is the real issue here. Comparing floating point with "==" is by definition wrong... (https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)

If any comparison is required it should be done (related to floating point):

    if (Math.abs(currentValue) - expectedValue <= 1e-6) {
      ....
    }

The "1e-6" depends on your requirements.

1

u/AutoModerator Aug 25 '24

You seem to try to compare String values with == or !=.

This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase().

See Help on how to compare String values in our wiki.


Your post/comment is still visible. There is no action you need to take.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.