Contents    Page-10    Prev    Next    Page+10    Index   

Consider the following code:


   i = 200;
   j = i;
   i++;
   j++;
What is the value in Java of ( i == j ) ,
if i and j are both int or both Integer?

  • A: true for both cases
  • B: true for int, false for Integer
  • C: false for int, true for Integer
  • D: false for both cases
  • E: WTF

    Answer: B

    When applied to an int, ++ increments the value, and == tests numerical equality. When applied to an Integer, ++ causes a new value to be found or created. Since 200 is beyond the range of the Integer cache, two new Integers are created, at different addresses. For Integer (and any reference or capital-letter type in Java), == tests equality of pointer values, guaranteed to be false in this case.

    The Moral: Never use == to compare values of Integers in Java. It works for small Integer values, but is dangerous because it does not work for larger values.