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?

1
  • The answer here will answer your question Commented Oct 24, 2014 at 2:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.