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

后端 未结 7 1669
伪装坚强ぢ
伪装坚强ぢ 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:09

    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.

提交回复
热议问题