04 July 2013

Right to Equality..


Consider following code:



First two lines print the output as:

a==b : true
c==d : false



Since primitives are checked for value rather than the address, first check returns true as expected. Similarly, since two different objects are compared in line 2, the outcome is expected.

But what about remaining lines ?
The outcome is:
true  // line 3
false // line 4 

false // line 5

Why ?
The reason is that Java internally caches the int values between -128 and +127 as a preloaded array.
So if the argument of valueOf function is between -128 and +127 (both inclusive), then an int value from cache array is auto-boxed and returned.  Else a new Integer object is created and is returned. This is internally managed by a nested class IntegerCache's cache array. 

User can specify the cache size by setting property java.lang.Integer.IntegerCache.high during the JVM startup. However, the value set must be more than 127 since the code in Integer class takes the max value between 127 and the value of this property.

For example, if above code is run by adding this property:

java -Djava.lang.Integer.IntegerCache.high=400 IntegerTest

Output is true for lines 3 and 4 and is false for line 5.