The answer to this question lies within the understanding of Autoboxing specified by Java programming language.
The variation in results of a == b
happens because any integer between -128 to 127 are cached by the Integer
class. When an int
within this range is created it is retrieved from IntegerCache
rather than creating a new Integer object.
Is this a bug? Of course not!
The Java class Integer is also called wrapper class because it provides an object that wraps an int
primitive data type. In Java, comparing two value object is not straight forward. We should override the Object.equal
method (and also the Object.hashCode
) and use it to determine when two objects are equal. Using the ==
operator, in this case, we’re comparing the two physical object addresses. Java requires the new operator to create objects, which will be all stored on the JVM’s Heap. Local variables are stored on the JVM’s Stack, but they hold a reference to the object, not the object itself.
In first case when we check if a == b
, we’re actually checking if both the references are pointing at the same location. Answer to this is NO!
But what happens when a & b are 50? To answer this we should have a look at the below Integer.valueOf
method.
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
We are using the Autoboxing
Java function through this Integer.valueOf
method to compare a == b
. With the aim of optimizing the resources use, the Integer
class maintains a cache memory of Integer
instances. This way, all the new Integer requests with a value between -128 and IntegerCache.high
(configurable) will return an identical object allocated once. So, when we ask if a == b, we get true because, behind the scene, a and b are pointing to the same memory location.
Now another question arises: Does this approach involve in instance sharing problems? The answer fortunately is no, because Integer was defined as an immutable object and that means if you want to modify it, you have to get a new instance… exciting, isn’t it?
Shishir