Warrior Warrior - 1 month ago 18
Java Question

Java Wrapper equality test

public class WrapperTest {

public static void main(String[] args) {

Integer i = 100;
Integer j = 100;

if(i == j)
System.out.println("same");
else
System.out.println("not same");
}

}


The above code gives the output of
same
when run, however if we change the value of
i
and
j
to 1000 the output changes to
not same
. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.

Answer

In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):

private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Integer(i - 128);
    }
}

See also: http://www.owasp.org/index.php/Java_gotchas

Comments