← All blog posts

Integer Class, auto-boxing and Caching

July 1, 2024 · Programming

Today, i decided to search a little the latest j2sdk sources. My initial search began with the usage of final modifier in the signature of a method. What is its exact usage, etc.

I wrote some sample programs and decompiled them, finding nothing of interest. Then i tried to investigate auto-boxing. I wrote a sample program that calls a method that has an Integer class as parameter. Something like that:

public void bar(Integer i) { ... }

int i = 1;
System.out.println(i);

When i used auto-boxing, the compiler used the Integer.valueOf(int) method. So i started searching if it is more optimized to use auto-boxing, or not.

When i changed the i variable to Integer type, and called normally the constructor of the Integer class, i realized that the constructor was invoked normally, with int as parameter.

The mystery solved when i read the original Integer class sources.

The contructor simply instantiates a new Integer object. On the other hand, the Integer.valueOf(int) does the following:

public static Integer valueOf(int i) {pre
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}

return new Integer(i);
}

The valueOf method uses an cache object and keeps 256 integers cached all the time. The pre for the integer cache follows:

private static class IntegerCache {
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}

So, if you use auto-boxing (or simply use the Integer.valueOf() method) instead of the normal constructor, you get a cached integer reference instead of a new object. This is an documented feature (see the Integer.valueOf(int) javadoc entry), and is demostrated by the following code.

public class Foo {
public static void main(String[] args) {
Integer i = new Integer(10);
Integer ii = new Integer(10);
Integer iii = Integer.valueOf(10);
Integer iiii = Integer.valueOf(10);

System.out.println("i == ii - " + (i == ii));
System.out.println("ii == iii - " + (ii == iii));
System.out.println("iii = i - " + (i == iii));
System.out.println("iiii = iii - " + (iiii == iii));
}
}

Sample executiion output follows:

bkarak$ java Foo
i == ii - false
ii == iii - false
iii = i - false
iiii = iii - true

But the caching works only with the Integer.valueOf(int) method. See the implementation of the Integer.valueOf(String,int) for example:

public static Integer valueOf(String s, int radix) 
throws NumberFormatException {
return new Integer(parseInt(s,radix));
}

This method always returns a new Integer object. Doh!