Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
The two keywords change control flow in different ways. In this loop, continue handles i == 3, break handles i == 6, and the print statement runs for every other reached value.
for (int i = 1; i <= 8; i++) {
if (i == 3) {
continue;
}
if (i == 6) {
break;
}
System.out.print(i + " ");
}1 2 4 5When i is 3, continue sends control to the next iteration of the for loop. The loop does not leave completely. When i is 6, break sends control outside the loop, so the loop ends immediately. That is why continue removes one reached value from the output, while break also prevents all later values from being processed.
What output does the loop produce?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
At i == 3, the continue statement skips everything below it in the current iteration. The break test is not reached, and System.out.print is not reached, so 3 is not printed. However, the for loop still performs its update expression, i++, before checking the loop condition again.
The value of i is 3 when continue runs. The update changes it to 4, and only then does the loop check i <= 8. The next iteration therefore begins with i equal to 4. Continue does not test the condition again with 3, and it does not end the loop.
if (i == 3) {
continue;
}
// The for loop performs i++ here.
// The next condition check uses i == 4.At i == 6, execution reaches the break test because the earlier continue test is false. The break statement exits the loop immediately. The print statement is below break, so 6 is not printed, and the for loop does not perform its update expression after break.
After leaving the loop at 6, execution continues with the first statement after the loop. The loop condition is not checked again, so i never advances to 7 or 8 inside this loop. Those values are not skipped iterations, because their iterations never begin.
After continue runs when i == 3, what is the next value of i whose loop condition is checked?
if (i == 3) {
continue;
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The loop begins with i equal to 1. The tests for 3 and 6 are both false, so 1 is printed and the update changes i to 2. The same path prints 2, then the update changes i to 3.
At 3, continue bypasses the break test and the print statement, then the update changes i to 4. Values 4 and 5 follow the normal path and are printed. At 6, break runs before the print statement and leaves the loop.
The complete result is 1 2 4 5. The missing 3 is a reached value whose iteration was cut short by continue. The missing 6 is a reached value whose iteration was cut short by break. Values 7 and 8 are different: break prevents their iterations from ever being reached.