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

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

    Autoboxing caches -128 to 127. This is specified in the JLS (5.1.7).

    If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

    A simple rule to remember when dealing with objects is - use .equals if you want to check if the two objects are "equal", use == when you want to see if they point to the same instance.

提交回复
热议问题