What is the output of: int i = 1; i = i++; System.out.println(i);
The post-increment operator `i++` first retrieves the current value of `i` (which is 1) for use in the assignment expression. Subsequently, `i` is incremented to 2. However, the assignment `i = ...` then takes the *original* value (1) and assigns it back to `i`, effectively overwriting the incremented value. This specific order of operations, where the assignment occurs *after* the value is retrieved but *before* the incremented value can persist, ensures `i` remains 1 when printed.
Why this answer
In Java, the expression `i = i++` uses the post-increment operator, which first stores the current value of `i` (1) for the assignment, then increments `i` to 2, but the stored original value (1) is then assigned back to `i`. Thus, `i` remains 1, and the output is 1.
Exam trap
The trap here is that candidates often assume `i++` always increments the variable before the assignment, leading them to choose 2, but they miss that the post-increment operator returns the original value for the expression, which is then assigned back.
How to eliminate wrong answers
Option A is wrong because the code compiles successfully; there is no syntax or type error. Option B is wrong because `i` is initialized to 1, and the post-increment does not result in 0; the value 1 is assigned back. Option C is wrong because although `i` is temporarily incremented to 2, the assignment overwrites it with the original value 1, so the final value is not 2.