Integer.valueOf(int i) method contains assesrt to check that IntegerCache more or equals 127.
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
The cache implementation looks like this
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
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++);
}
So you could increase cache size by passing property value. But implementation will not allows you to set cache size lower than 127 (or it does?). So why they place assertion in Integer.valueOf(). Do developers not trust own implementation?
I understand that if cache lower than 127 Integer.valueOf(int i) would return wrong value, but such just could not happen…
Is it necessary to have assert there?
This is precisely the purpose of assertions: to catch programming bugs. One wouldn’t catch any bugs by assuming there are none.