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

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

    It is memory optimization in Java related.

    To save on memory, Java 'reuses' all the wrapper objects whose values fall in the following ranges:

    All Boolean values (true and false)

    All Byte values

    All Character values from \u0000 to \u007f (i.e. 0 to 127 in decimal)

    All Short and Integer values from -128 to 127.

提交回复
热议问题