Using == operator in Java to compare wrapper objects
The key to the answer is called object interning. Java interns small numbers (less than 128), so all instances of Integer(n)
with n
in the interned range are the same. Numbers greater than or equal to 128 are not interned, hence Integer(1000)
objects are not equal to each other.
If you look at the source code for Integer
you'll see that Integer.valueOf(int)
pools all values -128 to 127. The reason is that small Integer values are used frequently and are thus worthy of being pooled/cached.
Taken straight from Integer.java
:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
Note that this pooling is implementation specific and there's no guarantee of the pooled range.
The answers about interning are correct in concept, but incorrect with terminology. Interning in Java normally implies that the Java runtime is performing the pooling (such as String's intern). In Integer's case it's the class itself that is doing the pooling. There's no JVM magic involved.
The above answer about Interning is right on. Something to consider though if you do:
Integer i3 = new Integer(10);
Integer i4 = new Integer(10);
You will not have the new objects since you have created new objects explictly. If you write the code as follows it will be interned:
Integer i3 = Integer.valueOf(10);
Integer i4 = Integer.valueOf(10);
They will now be the same object again. If you take a look at the valueOf Method inside of the Integer.java class in the src.zip file you can see where it checks to see if the value of the int is outside of -128 to 127 it calls the new Integer class otherwise it loads it from the cache.