3

This question came up in one of my interview questions for an internship position written in Java. Notice that the boolean function isSame actually declares 2 parameters as Integer class - not int, so I thought a and b are objects, correct?

public class ForLoop{

 public static boolean isSame(Integer a, Integer b) {
     return a == b;
 }

 public static void main(String []args){

    int i = 0;
    for (int j=0; j<500; ++j) {
        if (isSame(i,j)) {
            System.out.println("Same i = "+i);
            System.out.println("Same j = "+j);
            ++i;
            continue;
        } else {
            System.out.println("Different i = "+i);
            System.out.println("Different j = "+j);
            ++i;
            break;
        }
    }
    System.out.println("Final i = " + i);

 }
}

My first thought is that the for loop would terminate in the 1st run with the result Final i = 1, but to my surprise the final output is i = 129. The loop terminated when both i & j = 128.

  Same i = 126
  Same j = 126
  Same i = 127
  Same j = 127
  Different i = 128
  Different j = 128
  Final i = 129   

Can someone please explain?

user1803551
  • 12,965
  • 5
  • 47
  • 74
  • [The answer here](http://stackoverflow.com/questions/20877086/confusion-in-method-integer-valueofstring) will answer your question – Baby Oct 24 '14 at 02:23

1 Answers1

5

When testing Object types for equality use .equals(), as you have found -128 to 127 (inclusive) are pooled. The JLS-5.1.7 says in part,

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249