IntegerCache in JDK1.5


What is the O/p of following ?

Integer i1 = 20;
Integer i2 = 20;
Integer i3 = 200;
Integer i4 = 200;

if(i1 == i2){
System.out.println("True");
}else{
System.out.println("False");
}

if(i3 == i4){
System.out.println("True");
}else{
System.out.println("False");
}

if(Integer.valueOf(20) == Integer.valueOf(20)){
System.out.println("True");
}else{
System.out.println("False");
}

if(Integer.valueOf(200) == Integer.valueOf(200)){
System.out.println("True");
}else{
System.out.println("False");
}

The answer is
True
False
True
False
It is because in JDK1.5 there is a new concept called Caching Integer Objects.

Until JDK1.5 it didn’t matter whether to use Integer.valueof() or new Integer() methods to create an integer object.But with the jdk1.5 feature it is recommended to use Integer.valueOf().

Reason : In JDK1.5 the JVM caches Integer objects from range of -128 to 127 . So every time an integer object is create with value between the above mentioned range same object will be returned instead of creating the new object.

For the given statement
Integer i1 = 20.
The autoboxing features come into play which uses again the Integer.valueOf() method to create an object and every time will return same object.

Note: This will not happen for Integer i1 = new Integer(20). // Something similar to String pool

The Integer class has an inner class called IntegerCache with the following implementation.

private static class IntegerCache {
static final int high;
static final Integer cache[];

static {
final int low = -128;

int h = 127;
if (integerCacheHighPropValue != null) {
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}

private IntegerCache() {}
}

Since its an inner class, so the 256 objects will not be created until it is called for the first time. Hence, initial loading of the first integer object will be slow as cache array with 256 objects will be created.

The valueOf() method implementation is :


public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}