Why Comparison Of two Integer using == sometimes works and sometimes not?

1k Views Asked by At

I know that i am comparing reference while i'm using == which is not a good idea but i did not understand why is this happening.

Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
3

There are 3 best solutions below

0
On BEST ANSWER

The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf(), which is implicitly used by the autoboxing.

0
On

Integers between -128 and 127 are cached (Integers of the same value reference the same Object). Comparing your a and b references returns true, because they are the same Object. Your c and d are not in that range, so their reference comparison returns false.

4
On

Integer values between -128 to 127 are being cached.

See the below Source code:

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);
    }
}

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);
}