1
Integer int1 = 2;
Integer int2 = 2;
System.out.println(int1 == int2);   // ok

Run code

/Libray/.../jdk1.8.0_241.jdk/.../..java...
true
Process finished with exit code 0

Compare Double object

Double dou1 = 4.0;
Double dou2 = 4.0;
System.out.println(dou1 == dou2);

Run code

/Libray/.../jdk1.8.0_241.jdk/.../..java...
false
Process finished with exit code 0

I think it's possible to compare integers using autoboxing and unboxing, but why it doesn't work for Double?

3asyPe
  • 254
  • 1
  • 6
Ven Ren
  • 1,584
  • 1
  • 13
  • 24
  • 2
    Try the first one with larger integer values. – tobias_k Jul 31 '20 at 09:02
  • 4
    `Integer`s are objects. They should be compared with `.equals`. Two Integer objects with the same value might _happen_ to be the same object, but that should not be relied upon. – khelwood Jul 31 '20 at 09:03
  • 2
    If I recall correctly Integers from -128 to 127 are shared objects. For other ones new objects are created. Doing comparison from outside of that range will result in false as well. – Amongalen Jul 31 '20 at 09:05
  • 4
    Integers are cached and reused in range -128 .. 127. If you use `==` to compare integers outside of that ranged you will get false. – Pshemo Jul 31 '20 at 09:05
  • @Amongalen i try it more then 127, – Ven Ren Jul 31 '20 at 09:06
  • 1
    https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java – Murat Karagöz Jul 31 '20 at 09:07

0 Answers0