0

This was a question asked during a programming open interview. I'm not sure why the result for i=128. Could someone illuminate why 128 is the answer.

public static boolean isSame(Integer a, Integer b)
{
    return a == b;
}
 public static void main(String []args){
    int i = 0;
    for(int j = 0; i < 500; ++i, ++j)
    {
        if (isSame(i,j))
            continue;
        else
            break;
    }

    System.out.println(i);
 }
nitiger
  • 349
  • 4
  • 5
  • 18
  • 5
    PS. This is a *terrible* interview question because it relies on knowing JVM vagaries. I would not hire anyone who thinks this is a *good* question. – cyngus Oct 24 '14 at 00:15
  • step debugger is your friend! –  Oct 24 '14 at 00:22
  • @cyngus It's not "JVM vagaries"; pooled boxes are specified by the JLS for [-128..127]. – chrylis -cautiouslyoptimistic- Oct 24 '14 at 00:46
  • 1
    @cygnus While I agree that knowing the exact details of why it stops at 128 makes it a bad question, (Any candidate who quotes the JLS gets a downvote as too Sheldonian in my opinion), following the reasoning of the interviewee could be useful. A good candidate would know Integers are immutable, and hopefully would realize that they _could_ be cached, and have some theory about how Integers up to some "reasonable" number like 100, 128 or 256 would be cached and shared. Though I think that my answer might be "this code sucks, autoboxing is tricky, who wrote this crap". – user949300 Oct 24 '14 at 01:23
  • 1
    Thanks. I would actually think that writing code like this is deplorable in the first place. I mean if you want a function that takes Integer objects then why pass it anything but that in the call? – nitiger Oct 24 '14 at 03:52
  • @nitiger or, if it really is comparing Object references, it should take Objects as arguments for generality? And why are i and j separate variables when they always have the same value? – user949300 Oct 24 '14 at 15:23
  • @chrylis so we can quibble about semantics of whether this is a vagary of the JVM or a vagary of the Java language, but that is really irrelevant to the fact that it this sounds like someone's "gotcha!" question, which are fundamentally useless. – cyngus Oct 24 '14 at 16:21
  • @user949300 I agree that an extraordinary candidate would have that degree of thinking, but it is a bit of a leap to derive that Java makes this random optimization. A better point is maybe to realize you shouldn't be using "==" on Objects to establish an "equals" relationship. – cyngus Oct 24 '14 at 16:27
  • @nitiger Yes, in a code review I would reject code needlessly using Integer instead of int. Objects incur a huge relative overhead (unless your language specifies some clever tricks, ha ha) for storage of a primitive value. – cyngus Oct 24 '14 at 16:29
  • @cygnus In a code review I'd reject _every_ line of that code. Ok, maybe not the println. – user949300 Oct 24 '14 at 20:32

0 Answers0