What's the output of the following code?
class Main { //w w w .j a v a2 s .c o m public static void main(String[] args) { int i = 10; do while (i++ < 15) i = i + 20; while (i < 2); System.out.println(i); } }
d
If you attempted to answer question 5-1, it's likely that you would select the same answer for this question.
I deliberately used the same question text and variable names (with a small difference) because you may encounter a similar pattern in the OCA Java SE 8 Programmer I exam.
This question includes one difference: unlike question 5-1, it uses a postfix unary operator in the while condition.
The condition specified in the do-while loop evaluates to false (because 10<2 evaluates to false).
But the control enters the do-while loop because the do-while loop executes at least once-its condition is checked at the end of the loop.
This question prints out 32, not 30, because the condition specified in the while loop (which has an increment operator) executes twice.
In this question, the while loop condition executes twice.
For the first evaluation, i++ < 15 (that is, 10<15) returns true and increments the value of variable i by 1 (due to the postfix increment operator).
The loop body modifies the value of i to 31.
The second condition evaluates i++<15 (that is, 31<15) to false.
But because of the postfix increment operator value of i, the value increments to 32.
The final value is printed as 32.