I just saw code similar to this:
public class Scratch
{
public static void main(String[] args)
{
Integer a = 1000, b = 1000;
System.o
If we check the source code of the Integer
class, we can find the source of the valueOf method just like this:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
This explains why Integer
objects, which are in the range from -128 (Integer.low
) to 127 (Integer.high
), are the same referenced objects during the autoboxing. And we can see there is a class IntegerCache
that takes care of the Integer
cache array, which is a private static inner class of the Integer
class.
There is another interesting example that may help to understand this weird situation:
public static void main(String[] args) throws ReflectiveOperationException {
Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[132] = newCache[133];
Integer a = 2;
Integer b = a + a;
System.out.printf("%d + %d = %d", a, a, b); // The output is: 2 + 2 = 5
}