Archive for April, 2015

Comparing Wrappers other than String

public class A {
public static void main(String[] args) {
Integer i1=100; Integer i2=100;
Integer i3=200; Integer i4=200;
System.out.println(i3==i4);//false -- why ??


The Integer wrapper class interns the objects from -127 to +128. So all Integers with a value less than 128 are the same as they are interned. The values greater than 128 are not the same because they are not interned.

The JVM will create a cache of objects(something similar to the string constant pool) for the above range and assigns the same object(if it already exists) when ever a new object with the same value is created. So in your case, the two Integers for 100 will use the same object and the ones for 200 won’t be the same.

you assign a integral literal to a Integer reference, it will invoke the Integer.valueOf(..) method.

This method uses the famous Fly-weigh pattern. That is that the -128~127 integers are cached. So the “i1==i2” will be true. Of course, you can change the cache range by setting IntegerCache.low or IntegerCache.high which are static variables.

Always compare wrapper classes with equals(e).