Reputation: 1189
I am confused on a few things regarding using double.
If i were to initialize 2 doubles with the same literal, would == always evaluate to true? for example, if following outputs true but i don't know if this is by chance:
double a = .1d;
double b = .1d;
System.out.println(a==b);
I get the same result when using Double instead of double:
Double a = .1d;
Double b = .1d;
System.out.println(a.equals(b));
According to Double documentation, equals() return true if doubleValue() are equal.
So the question is, is "==" for double and "equals()" for Double guaranteed to evaluate to true for 2 variables initialized using the same literal?
When would they evaluate to false? Is this when arithmetic operations are involved?
Thanks
Upvotes: 0
Views: 5283
Reputation: 638
In general ==
is an operator which checks for equality. Object variables are references so it checks for reference or address equality. In the case of primitive data types representing values in the memory that also means that it checks for value equality.
The method equals(~)
checks for value or content equality. You do not use it for primitive data types but for Objects.
That is also the case for double and Double. The problem which is arising with doubles is the mismatch of the values induced by rounding errors.
Some arithmetic operations may handle rounding differently so you might get false
for value equality even if you think it should be equal.
It should be stated that even if the rounding rules are a bit inconsistent arithmetic operations are deterministic so that inconsistency can be handled.
Upvotes: 1