Sub topic 8
Exit or skip an iteration with break and continue
A loop repeats work. Each pass through a loop is an iteration. The statements inside the loop are its body.
Sometimes you want more control over an iteration:
- Use
breakto leave a loop early. - Use
continueto skip the rest of the current iteration and move toward the next one.
This chapter assumes you have seen Java’s for, while, and do-while loops, as well as if statements and arrays. You will use those ideas to decide what happens when a loop meets a special case.
Leave a loop with break
A loop condition is a true-or-false test that controls repetition. A loop can finish because its condition becomes false. But you can also use break to leave the loop before that happens.
Try this complete program. Save it as Main.java, then run javac Main.java followed by java Main. Each later Java example is also a complete program you can run the same way.
public class Main {
public static void main(String[] args) {
for (int number = 1; number <= 5; number++) {
if (number == 4) {
break;
}
System.out.println(number);
}
System.out.println("Loop finished");
}
}The output is 1, 2, 3, and then Loop finished, each on its own line.
Here is what happens:
- The loop starts with
numberequal to1. - The program prints
1,2, and3on separate iterations. - When
numberis4, theifcondition is true. breakends the loop. The program does not print4.- Execution continues with the statement after the loop, which prints
Loop finished.
The loop condition would allow number to reach 5, but break stops the loop first. The for loop’s update, number++, does not run after that break.
A break leaves the loop, not the whole program. In this example, the statement after the loop still runs.
Use break when you have found enough
One common use of break is to stop searching once you find what you need. An array is a group of values stored under one name.
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9, 12};
int target = 9;
boolean found = false;
for (int value : values) {
if (value == target) {
found = true;
break;
}
}
if (found) {
System.out.println("Found the target");
} else {
System.out.println("Target not found");
}
}
}This program prints Found the target.
The variable found is a flag: a true-or-false value used to remember something. It starts as false. When the loop reaches 9, the program changes the flag to true and leaves the loop. The loop does not need to check 12.
If the target is not in the array, break never runs. The loop visits every value, and found stays false.
Skip the rest of an iteration with continue
Unlike break, continue does not normally end the loop. It skips the remaining statements in the current iteration. The loop then follows its usual steps to decide whether to repeat.
public class Main {
public static void main(String[] args) {
for (int number = 1; number <= 5; number++) {
if (number == 3) {
continue;
}
System.out.println(number);
}
System.out.println("Loop finished");
}
}The output is 1, 2, 4, 5, and then Loop finished, each on its own line.
When number is 3, the program reaches continue. It skips the print statement for that iteration. The loop then goes on to 4.
| Value of `number` | What happens |
|---|---|
| `1` | Print `1`. |
| `2` | Print `2`. |
| `3` | Run `continue`; skip the print statement. |
| `4` | Print `4`. |
| `5` | Print `5`. |
Compare the two keywords:
breaksays, “I am done with this loop.”continuesays, “I am done with this iteration.”
Both skip statements that remain in the current loop body. The difference is whether the loop can run another iteration.
Use continue to skip unwanted values
Suppose an array contains test scores, but a negative value means a score was not recorded. You can skip that value while still processing the rest.
public class Main {
public static void main(String[] args) {
int[] scores = {8, -1, 6, 10};
int total = 0;
for (int score : scores) {
if (score < 0) {
continue;
}
total = total + score;
}
System.out.println("Total: " + total);
}
}The output is Total: 24.
The value -1 causes continue to run, so the program does not add it to total. The loop still visits 6 and 10.
Using break in that same place would produce a different result. It would stop at -1, leaving the later scores uncounted. Choose continue when one value should be skipped, but later values still matter.
What happens after continue?
The next step after continue depends on the kind of loop. This matters because a loop often needs to change a value before it can finish.
| Loop type | Next step after `continue` |
|---|---|
| Basic `for` | Run the update in the loop header, then test the condition. |
| `while` | Test the condition again. |
| `do-while` | Test the condition at the bottom of the loop. |
| Enhanced `for` | Move to the next array element, if there is one. |
An update changes a value used by the loop. In a basic for loop, it is often the final part of the header, such as number++.
The following diagram shows one possible order of checks inside a basic for loop. The continue path still goes through the update. The break path does not.
In a while loop, keep the update reachable
A while loop tests its condition after continue. It does not have a separate update in its header. If the update is below continue, it will be skipped.
This example updates number before checking whether to skip printing it:
public class Main {
public static void main(String[] args) {
int number = 0;
while (number < 5) {
number++;
if (number == 3) {
continue;
}
System.out.println(number);
}
}
}The program prints 1, 2, 4, and 5, each on its own line. On the iteration where number becomes 3, the update has already happened. The next condition test still sees a value that can eventually reach 5.
Be careful if you move number++ below the continue. Once number reaches 3, the loop would skip the update on every following iteration. The condition number < 5 would stay true, so the loop would not finish.
In a do-while loop, continue reaches the condition
A do-while loop tests its condition at the bottom. A continue skips the rest of the body but still reaches that test.
public class Main {
public static void main(String[] args) {
int number = 0;
do {
number++;
if (number == 3) {
continue;
}
System.out.println(number);
} while (number < 3);
System.out.println("Finished at " + number);
}
}The program prints 1, 2, and then Finished at 3, each on its own line.
When number becomes 3, continue skips the print inside the loop. The program then tests number < 3. That condition is false, so the loop ends. A continue does not guarantee another iteration; it leads to the loop’s next test.
Break and continue in nested loops
A nested loop is a loop inside another loop. With the plain forms shown in this chapter, break and continue act on the nearest enclosing loop.
In the next program, the outer loop chooses a row. For each row, the inner loop chooses columns. The inner loop skips column 1 and stops when it reaches column 3.
public class Main {
public static void main(String[] args) {
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 4; column++) {
if (column == 1) {
continue;
}
if (column == 3) {
break;
}
System.out.println(row + "," + column);
}
}
System.out.println("Done");
}
}The output is:
0,00,21,01,2Done
For row 0, the inner loop prints column 0, skips column 1, and prints column 2. At column 3, break ends the inner loop. The outer loop then moves to row 1, where the inner loop starts again.
The break is inside an if statement, but it does not merely leave the if. It leaves the inner loop. The continue also applies to the inner loop, so it skips one column iteration, not the rest of the row.
Stop more than one loop
If you need to stop both loops, one clear approach is to use a flag. The inner loop sets the flag and breaks. The outer loop checks the flag and breaks as well.
public class Main {
public static void main(String[] args) {
boolean stop = false;
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
if (row == 1 && column == 1) {
stop = true;
break;
}
System.out.println(row + "," + column);
}
if (stop) {
break;
}
}
System.out.println("Stopped");
}
}The program prints 0,0, 0,1, 0,2, and 1,0, each on its own line. It then prints Stopped.
The condition uses &&, which means both comparisons must be true. When the program reaches row 1, column 1, it sets stop to true and leaves the inner loop. The outer loop sees the flag and leaves too.
Java also has labeled forms of break and continue. The examples here use the plain, unlabeled forms.
Common mistakes to check
Expecting continue to end the loop
If a later value still needs processing, continue is useful. If the loop must stop completely, use break.
For example, skipping a missing score should not prevent you from adding later scores. But after finding a single target, you may have no reason to keep searching.
Putting needed work after continue
Any statement after continue in the same iteration is skipped. That includes printing, adding to a total, and changing loop variables.
Trace the path where the if condition is true. Ask which statements will not run. In a while or do-while loop, pay special attention to changes needed for the loop to finish.
Thinking break skips only one statement
break exits the loop even if more statements remain in its body. To skip only the current iteration and allow the loop to repeat, use continue.
Expecting break to leave every surrounding loop
A plain break in an inner loop leaves that inner loop. The outer loop can continue. Use a flag and a second break when both loops need to stop.
There is also one useful detail about switch. A switch is a Java construct that selects code based on a value. If a plain break is inside a switch that is inside a loop, the break exits the switch, not the loop. A plain continue inside that switch applies to the enclosing loop.
Forgetting the condition still matters
A continue does not force a new iteration. After the appropriate update, the loop tests its condition. If the condition is false, the loop finishes.
A break is different: it leaves the loop without waiting for the condition to become false.
Practice
For each question, trace one iteration at a time. Check where execution goes after each break or continue.
Exercise
A for loop visits the numbers 1 through 5. It runs continue when the number is 2 and prints the number otherwise. What does it print?
Show answer
It prints 1, 3, 4, and 5. The iteration for 2 skips the print statement, but the loop continues.
Exercise
The same loop runs break instead of continue when the number is 2. What does it print from inside the loop?
Show answer
It prints only 1. When the number reaches 2, break ends the loop before the print statement.
Exercise
A while loop increases count at the end of its body. An if statement before that update runs continue whenever count is 3. What can go wrong?
Show answer
Once count reaches 3, continue skips the update. If the loop condition stays true at 3, the loop will repeat without finishing.
Exercise
An inner loop finds a target and runs break. Does the outer loop stop too?
Show answer
No. A plain break exits the inner loop. The outer loop can continue unless it has its own way to stop, such as checking a flag and running another break.