I'm looking into the identity of integers, I know an Object is identical to another Object when they occupy the same memory space, it can be shown by the following code
Integer a = 1;
Integer b = a;
System.out.println(a == b);
this will return true
because the reference b
is pointing to a
, when looking at equality there are conditions that needs to be met for any Object to be equal to another, using the following code
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b);
this will return false
because a
and b
are two different objects, and this makes sense, but here is where I get confused, if I write
Integer a = 1;
Integer b = 1;
Integer c = 1000;
Integer d = 1000;
System.out.println(a == b);
System.out.println(c == d);
the first print will return true
and the last will return false
, since all four integers are different objects, they should return false
, why does the first return true
? I looked at the Integer.valueOf()
method (based on my knowledge of boxing and unboxing) and found that once a value is bigger than 128 (1 Byte) its cached differently, why is that? can anyone perhaps explain this ?