0

Here is my code:
I was checking equals method and == operator.

I know, if we are not using primitive data types, we should prefer equals method. But here it is behaving differently. Aren't d1 and d2 same references.

Integer i1 = 2;
Integer i2 = 2;
System.out.println(i1==i2);
Double d1 = 2.2;
Double d2 = 2.2;
System.out.println(d1==d2);

Output is:

true 
false

Why is it false in case of Double? Thank you.

Jay Patel
  • 1,156
  • 6
  • 15
  • 35
  • "Aren't d1 and d2 same references."? No, they are two different objects which both happen to wrap the same `double` value. – azurefrog Oct 09 '15 at 03:07
  • Then why is it true in case of Integer? – Jay Patel Oct 09 '15 at 03:08
  • 1
    Because values between -128 and 127 are a special case. Try it with `Integer` of value `2000` and you'll see. One sec and I'll find the reference questions. – azurefrog Oct 09 '15 at 03:09
  • 1
    See [this question](http://stackoverflow.com/questions/3637936/java-integer-equals-vs) regarding Integer caching. – azurefrog Oct 09 '15 at 03:11
  • 1
    [This question](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) is specifically about `String`, but the reference vs value check concept is the same for any class. – azurefrog Oct 09 '15 at 03:14

0 Answers0