Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?

Viewed 56990
class D {
    public static void main(String args[]) {
        Integer b2=128;
        Integer b3=128;
        System.out.println(b2==b3);
    }
}

Output:

false

class D {
    public static void main(String args[]) {
        Integer b2=127;
        Integer b3=127;
        System.out.println(b2==b3);
    }
}

Output:

true

Note: Numbers between -128 and 127 are true.

8 Answers

Other answers describe why the observed effects can be observed, but that's really beside the point for programmers (interesting, certainly, but something you should forget all about when writing actual code).

To compare Integer objects for equality, use the equals method.

Do not attempt to compare Integer objects for equality by using the identity operator, ==.

It may happen that some equal values are identical objects, but this is not something that should generally be relied on.

if the value is between -128 and 127, it will use the cached pool and this is true only when auto-boxing. So you will have below:

    public static void main(String[] args) {
        Integer a  = new Integer(100);
        Integer b = new Integer(100);
        System.out.println(a == b);         // false. == compare two instances, they are difference
        System.out.println(a.equals(b));    // true. equals compares the value

        Integer a2 = 100;
        Integer b2 = 100;
        System.out.println(a2 == b2);       // true. auto-boxing uses cached pool between -128/127
        System.out.println(a2.equals(b2));  // true. equals compares the value

        Integer a3 = 129;
        Integer b3 = 129;
        System.out.println(a3 == b3);       // false. not using cached pool
        System.out.println(a3.equals(b3));  // true. equals compares the value
    }
}
Related