-7

I get that this is a dumb question but I couldn't figure this out on google so this is my last resort.

Why is it that when I try to compare two doubles that are variables that I know are equal, it returns false? Here's an example that I hope is more clear:

double x = 323.23
double y = 323.23
System.out.println(x==y)

Output:

false

Why does this happen? Also, why does it print true if you just compare two doubles that are not variables or a double that is a variable and a double that is not? example:

double x = 323.23
System.out.println(x==323.23)
System.out.println(323.23==323.23)

output:

true
true
Roman C
  • 49,761
  • 33
  • 66
  • 176

1 Answers1

-7

You should not compare doubles on an objet level. Your sample prints true because the compile just optimizes your code so that x and y point to the same object. Instead use Double.equals(). If you think about how doubles can be represented even equal values can have different bit configurations. If checking lesser/greater use the Double.compareTo() method.

Hannes
  • 2,018
  • 25
  • 32