Following the topic about constant pool.
Let’s look inside the source code JDK 1.6, java\lang\Integer.java :

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

From the source we can see when the value is -128 to 127 it’ll using cache / constant-pool.
So when we run the following code:

Integer i = 20;
Integer i2 = 20;
Integer i3 = 170;
Integer i4 = 170;
System.out.println(“i==i2 : ” + (i==i2) ); // true
System.out.println(“i==i2 : ” + (i3==i4) ); // false

Only value -128 until 127 will be cache. And of course the operator new wil create new object : new Integer(10)!=10.

Advertisements