I wrote the simple code:
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);
}
But, strangely, the result is as below:
true
false
Can you guys please explain why the difference occurs?
Integers are objects, the == operator might "work" (in the sense of what you expect it to do - to compare values) only for numbers between [-128,127]. Look at the JLS - 5.1.7. Boxing Conversion:
If the value p being boxed is
true,false, abyte, or acharin the range \u0000 to \u007f, or anintorshortnumber between -128 and 127 (inclusive), then letr1andr2be the results of any two boxing conversions ofp. It is always the case thatr1 == r2.
The values you're comparing are not in the range, the result is evaluated to false. You should use Integer#equals instead, or simply use the lovely primitive int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With