Question 1
What is the output of the following program?
public class Main {
public static void main(String[] args) {
int i = 0;
int sum = 0;
do {
i++;
if (i == 2) {
continue;
}
sum += i;
} while (i < 4);
System.out.println(sum);
}
}A. 10
This forgets the skip — it is 1+2+3+4, the total if continue never fired. i=2 is skipped, so 2 is never added.
B. 6
Stops the loop one pass early, summing 1+2+3 or similar. i takes 1, 2, 3 and 4 because the condition i < 4 is tested after the body, so 4 is still added.
C. 8Correct answer
Correct: i takes 1, 2, 3, 4 and continue skips the sum only for i=2, so sum = 1 + 3 + 4 = 8 (JLS 8 §14.13, §14.16).
D. It loops forever
Assumes continue skips the increment and stalls at i=2. In a do/while, continue jumps to the while CONDITION, and i was already incremented at the top of the body, so the loop still terminates.
Explanation
i takes 1, 2, 3, 4. continue skips the sum only for i=2 (then jumps to the while CONDITION, so no infinite loop — It loops forever is wrong). sum = 1 + 3 + 4 = 8. 10 forgets the skip.