5

Recently i came across this question

int i = 10;
while (i++ <= 10) {
    i++;
}
System.out.print(i);

The answer is 13 , can some please explain how is it 13?

4
  • 7
    What do you think the answer should be, and why? Commented Jul 28, 2015 at 0:46
  • The postincrement operator applies after (or "post") the expression in which it appears; but before any other expression is evaluated. Commented Jul 28, 2015 at 2:03
  • This is tricky. You might expect the answer to be 12. Why? Because the relational condition evaluation and the branch out of the loop might be assumed to be atomic. It obviously isn't, but it's not an irrational assumption. It is hard to conceive that Java "stores" the increment operation and "inserts" it after the relational condition is evaluated, but before the branch out of the loop. I wonder what the code produced by this looks like at the assembler/machine language level. Commented Feb 25, 2021 at 1:55
  • Conversely, this could boil down to storing the evaluation of the relational condition in a boolean (bit/byte?), performing the increment operation, and then performing the branch-if operation on the stored boolean. Commented Feb 25, 2021 at 2:03

2 Answers 2

9
  • i = 10. Look at i, compare to 10
  • i = 10. 10 <= 10, so enter the loop.
  • i = 10. increment i (as per the while expression)
  • i = 11. In the loop, increment i
  • i = 12. Look at i, compare to 10
  • i = 12. 12 is not <= 10, so don't enter the loop.
  • i = 12. Increment i (as per the while expression)
  • i = 13
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , i missed the last step of increment in while loop .
1

This is one of the alternative ways I could wrap my head around this. Let f(ref i) be a function which takes in i by reference and increment it it's value by 1. So f(ref i) = i + 1

Now that we have f(ref i), the above code can be written as

int i = 10
while( (f(ref i) -1) <=10 )
{
   f(ref i);
}

I would replace f(ref i) with equivalent i values on its return and get the answer like

while(11 - 1 <= 10) {12}
while (13 -1 <= 10) -> break;

so i = 13.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.