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

后端 未结 7 1668
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 07:58
class D {
    public static void main(String args[]) {
        Integer b2=128;
        Integer b3=128;
        System.out.println(b2==b3);
    }
}

7条回答
  •  一生所求
    2020-11-21 08:12

    Using primitive data types, ints, would produce true in both cases, the expected output.

    However, since you're using Integer objects the == operator has a different meaning.

    In the context of objects, == checks to see if the variables refer to the same object reference.

    To compare the value of the objects you should use the equals() method E.g.

     b2.equals(b1)
    

    which will indicate whether b2 is less than b1, greater than, or equal to (check the API for details)

提交回复
热议问题