3

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?

The111
  • 5,757
  • 4
  • 39
  • 55
Dat Nguyen
  • 1,881
  • 17
  • 36

1 Answers1

7

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, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == 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.

Maroun
  • 94,125
  • 30
  • 188
  • 241