Integer Class, auto-boxing and Caching
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);
}