Java interview: for loop, object / class references and associated limit

This question came up in one of my interview questions for an internship written in Java. Note that the logical function isSame

is actually announces 2 parameter as a Integer

class - not int

, so I thought that a

and b

are the objects, right?

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 loop for

will end on the first run with a result Final i = 1

, but to my surprise, the final result i = 129

. The loop ends when both i and 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?

+3


source to share


1 answer


When testing types Object

for equality .equals()

, as you found -128 to 127 (inclusive) are concatenated. JLS-5.1.7 says in part,



If the value of p in a box is true, false, byte, or char in the range \ u0000 to \ u007f, or int

or short

between -128 and 127 (inclusive), then let r1 and r2 be the results of any two box transformations of p. It always happens that r1 == r2.

+4


source







All Articles