Reputation: 177
Thanks in advance... Please explain why following happens :
Integer i1 = 6;
Integer i2 = 6;
(i1 == i2)
will return true.
while
Double d1 = 6.5;
Double d2 = 6.5;
(d1 == d2)
will return false.
Why is that? There will be only one object created in both the cases still they behave differently. Using equals method would be better but I was surprised by this behaviour and just wanted to know.
Upvotes: 2
Views: 145
Reputation: 1570
You are comparing Integer (capital I) objects by reference, which is not the "proper" way to compare objects in java.
References to some integers are cached in order to optimize for performance. This is why comparing certain Integer (capital I) objects by reference seems to work in a few cases in Java.
This is NOT a behavior that the Java developer is expected to rely on or make use of, as it is unreliable, may change, and makes code more difficult to understand.
Upvotes: 4