Originally posted by Sathya Shanmugam:
hi Java folks,
Could anyone give some explanation for the example below
Integer i3 = 1000;
Integer i4 = 1000;
if (i3 == i4) System.out.println("same object");
if (i3.equals(i4)) System.out.println("meaningfully equal");
if (i3 != i4) System.out.println("different objects");
o/p
same object
meaningfully equal
different objects
how come its displaying both same and different objects. pls give me some explanation..
Thanks
I don't see how both same and different can be printing, because the conditions in those statements are opposite.
The issue here has to do with boxing.
The language specification guarantees that ints in the range of -128 to 127 will be boxed into the same Integer if they are autoboxed.
However, individual JVMs might box other ints to the same Integer.
So the output you get will depend on the JVM.
But in this particular code, the language specification does not guarantee that i3 and i4 refer to the same object.