Java – compare 2 integers, strange behavior

See the English answer > why is 128 = = 128 false but 127 = = 127 is true when comparing integer wrappers in Java? 6

public static void main(String[] args) {
    Integer i1 = 127;
    Integer i2 = 127;
    boolean flag1 = i1 == i2;
    System.out.println(flag1);

    Integer i3 = 128;
    Integer i4 = 128;
    boolean flag2 = i3 == i4;
    System.out.println(flag2);
}

However, strangely, the results are as follows:

true
false

Can you explain why this difference occurs?

Solution

Integers are objects, and the = = operator may "work" (in the sense you expect it – compare values) only for numbers between [- 128127] Look at JLS – 5.1 7. Boxing Conversion:

The value you want to compare is out of range, and the result will be evaluated as false You should use integer #equals, or only love primitive int

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>