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,617
  • 4
  • 36
  • 55
Dat Nguyen
  • 1,841
  • 16
  • 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
  • 91,013
  • 29
  • 181
  • 233
  • 1
    He could also use int instead to make it work. – Icy Creature Dec 18 '14 at 09:24
  • 2
    "the == operator might work only for numbers between ..." this is slightly misleading; the `==` operator works correctly regardless of the numbers (it correctly checks reference equality and reports true or false). The problem is not that `==` doesn't _work_, the problem is that it doesn't do what the OP expects, mainly due to reference equality not being guaranteed for Integers derived from values larger than 127. – davmac Dec 18 '14 at 09:27
  • @davmac By "work" I mean according to OP's needs. Not functionality of the operator itself. – Maroun Dec 18 '14 at 09:28
  • @MarounMaroun I understand that, but I'm suggesting that you re-word it since 'work' has a general meaning that goes well beyond "what the OP needed". – davmac Dec 18 '14 at 09:29
  • @davmac Thanks, edited. I hope it's clearer now. – Maroun Dec 18 '14 at 09:30