This is because of how autoboxing and the Integer class work.
Autoboxing means that the compiler automatically replaces code like this:
with the following:
You know that using == on non-primitive values returns true only if the values on both sides of the == operator refer to the exact same object. (It returns false if you have two different objects, even if those objects have the same value).
So, the question now is, why does this print true:
but why does this print false:
The answer is in the way that Integer.valueOf(...); works. This method does not always return a new Integer object - instead, it manages a cache that contains Integer objects with all the values between -128 and 127. If the value you pass into the method is in that range, it will return the pre-created object in the cache. In the first example with the value 42, the variables i1 and i2 will therefore refer to the same Integer object (that comes from the cache). In the second example with the value 1000, you will get two distinct Integer objects, because 1000 is outside of the range of the cache.
Nikhil Kumar C wrote:
Is there any specific reason why only integer values between -128 to 127 are being cached?
The specification defines the types and the ranges that must be cached. It does not define what should happen to the values of other types, or if they are outside of the required ranges.
The current Sun java implementation caches as required, plus... (1) it also caches long values, which is not required, and (2) there is a switch to allow the user to increase the range (caching values which are not required).
To me it seems logical that the reasons the specification would call for cached
values are the usual - space and speed. On average, the code will run faster
and in less space with the cached primitives.