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

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

    I wrote the following as this problem isn't just specific to Integer. My conclusion is that more often than not if you use the API incorrectly, you sill see incorrect behavior. Use it correctly and you should see the correct behavior:

    public static void main (String[] args) {
        Byte b1=127;
        Byte b2=127;
    
        Short s1=127; //incorrect should use Byte
        Short s2=127; //incorrect should use Byte
        Short s3=128;
        Short s4=128;
    
        Integer i1=127; //incorrect should use Byte
        Integer i2=127; //incorrect should use Byte
        Integer i3=128;
        Integer i4=128;
    
        Integer i5=32767; //incorrect should use Short
        Integer i6=32767; //incorrect should use Short
    
        Long l1=127L;           //incorrect should use Byte
        Long l2=127L;           //incorrect should use Byte
        Long l3=13267L;         //incorrect should use Short
        Long l4=32767L;         //incorrect should use Short
        Long l5=2147483647L;    //incorrect should use Integer 
        Long l6=2147483647L;    //incorrect should use Integer
        Long l7=2147483648L;
        Long l8=2147483648L;
    
        System.out.print(b1==b2); //true  (incorrect) Used API correctly
        System.out.print(s1==s2); //true  (incorrect) Used API incorrectly
        System.out.print(i1==i2); //true  (incorrect) Used API incorrectly
        System.out.print(l1==l2); //true  (incorrect) Used API incorrectly
    
        System.out.print(s3==s4); //false (correct) Used API correctly
        System.out.print(i3==i4); //false (correct) Used API correctly
        System.out.print(i5==i6); //false (correct) Used API correctly
        System.out.print(l3==l4); //false (correct) Used API correctly
        System.out.print(l7==l8); //false (correct) Used API correctly
        System.out.print(l5==l6); //false (correct) Used API incorrectly
    
    }
    
    0 讨论(0)
提交回复
热议问题