Integer class implemented Cache Technique for value range from -128 to 127 same as String Cache Technique which is based of Fly-Weight Design pattern.
They(Integer class developer) have decided to do this because they felt this range can be frequent used in Java code. So better to give in-built cache mechanism rather then always creating new Java Object.
If you Explore the Integer Java class You will find below piece of code used for Caching Technique.
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
Now the Question is if I felt I want to Increase the Caching integer range need to be greate then (-128 to 127) in this scenario we need to do below,
Either we need to pass the VM argument as -XX:AutoBoxCacheMax= where Size is high from above code snippet.
(Note: There is one Constraint like we can not set the Min value although.May be in future version of Java they can include this.)
If you are running from Eclipse then Please check the below Screen shot:
Step1:
Step2:
Here as per screen shot it can Cache from -128 till 500.
If you give integer value >500 again the behavior is same as per screen shot 1.
Again You need to pass the argument in VM arguments: section in Run Configuration.
If You pass in Program Arguments it will not Work.

