Java caches the integer objects in the range -128 to 127. So, when you try to assign a value in this range to a wrapper object, the boxing operation will invoke Integer.valueOf method and in turn it will assign a reference to the object already in the pool.

On the other hand, if you assign a value outside this range to a wrapper reference type, Integer.valueOf will create a new Integer object for that value. And hence, comparing the reference for Integer objects having value outside this range will give you false

From source code of Integer class for valueOf method

public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
return new Integer(i);

So you get same reference if value is between -128 to 127

Integer i = 126;
Integer i2 = 126;

Integer i3 = 128;
Integer i4 = 128;

System.out.println(i == i2); // true, reference pointing to same literal
System.out.println(i3 == i4); // false, reference pointing to different objects

But , when you create your integer instances using new operator, a new object will be created on Heap. So,

Integer i = new Integer(126);
Integer i2 = new Integer(126);

System.out.println(i == i2); // false
Integer constant pool in JAVA
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *