That is because "autoboxing" uses Integer.valueOf
, and Integer.valueOf
keeps a cache of Integer
objects for small integer values. Here's what the JLS says:
"If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2." JLS 5.1.7.
When you use the ==
operator to compare a pair of Integer
objects, it is actually comparing the object references. So your get true
if boxing gave you the same cached Integer
object, and false
if it didn't. Note that the JLS guarantees this behaviour for the ranges stated, but it also permits an implementation of the valueOf
method to cache a wider range of values.
The bottom line is that you should use equals(Object)
to compare Integer
objects ... unless you are really trying to test if they are the same object.
According to what I read, "Integer" should create an "object" in the heap, thus the two objects should be the same.
If your code explicitly does a new Integer(...)
, it is guaranteed to create a new Integer
object. However, autoboxing uses Integer.valueOf(...)
, and that is where the caching behaviour is implemented.