Reputation: 59
I got an Java question during my interview as below
public static boolean isSame(Integer a, Integer b){
return a==b;
}
public static void main(String[] arg){
int i=0;
for(int j=0;i<500;++i,++j){
if(isSame(i,j)){
continue;
}
else break;
}
}
The question is "i=?" at last.
I thought i would be 500 at last. But when I tried it in Eclipse i=128!
So I was wondering what is happening here.
Thanks
Upvotes: 2
Views: 2060
Reputation: 21
source code:
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) {
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);
}
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() {}
}
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);
}
Upvotes: 1
Reputation: 10119
This is because of auto boxing.
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
To know more about auto boxing refer here.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7
Upvotes: 0
Reputation: 425448
Comparing two Integer
objects using ==
will only return true
if they are the same object (ie the same exact instance), ie regardless of their value.
However, the values -128
to 127
are cached, so auto-boxing these values (which is occurring when you pass an int
in as an Integer
parameter) always returns the same instance of Integer
for a given value.
Values outside this range always result in a new instance of Integer
being created.
Upvotes: 7