The break and the continue are the two keywords that let you step out of a loop early or skip to the next pass. A label that is attached to a loop lets you leave the nested loops instead of only the innermost one. Used sparingly they make a loop express its own exit conditions clearly.
The previous lesson in this module covered "How Do for, while and do-while Loops Differ in Java?", and the next lesson in this module is about "How Do You Nest Loops to Print Grid Patterns and Tables?".
What does break do inside a loop?
The break ends the loop that contains it and it carries on with the statement after that loop. It is the way to say "we have found what we were looking for, stop searching" without writing a flag variable or a complicated condition.
public class FindFirstMatch {
public static void main(String[] args) {
int[] readings = {12, 45, 78, 91, 23};
int target = 78;
for (int i = 0; i < readings.length; i++) {
if (readings[i] == target) {
System.out.println("Found " + target + " at index " + i);
break;
}
System.out.println("checked index " + i);
}
System.out.println("scan finished");
}
}The output shows the scan stopping as soon as the target turned up.
checked index 0
checked index 1
Found 78 at index 2
scan finishedWithout the break the loop would have carried on and it would have checked the index 3 as well. The final line still prints either way, because the break leaves the loop rather than ending the program.
What does continue do inside a loop?
The continue abandons the rest of the current pass and it jumps straight to the next one. For a for loop it means that the update expression still runs, and for a while loop it means that the condition is re-tested. You use it to skip the data that you do not want without wrapping the rest of the body in an else.
public class SkipBadReadings {
public static void main(String[] args) {
int[] readings = {10, -1, 25, 0, 33};
int valid = 0;
int sum = 0;
for (int r : readings) {
if (r <= 0) {
continue;
}
valid++;
sum += r;
}
System.out.println("valid readings: " + valid);
System.out.println("sum: " + sum);
}
}Only the three positive readings counted.
valid readings: 3
sum: 68And written with the continue, the counting logic stays at the top level of the loop body instead of being buried in an else branch. That is the real benefit, because the interesting code is not indented one level deeper for the sake of a guard.
How do the labels let you break out of nested loops?
By default the break only ends the innermost loop. When you have two loops nested and you want to abandon both, you put a label before the outer loop and you repeat that label at the break.
public class NestedSearch {
public static void main(String[] args) {
int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 5;
boolean found = false;
outer:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == target) {
found = true;
System.out.println("Found " + target + " at row " + row + ", column " + col);
break outer;
}
}
}
System.out.println("scan finished, found=" + found);
}
}The output is this.
Found 5 at row 1, column 1
scan finished, found=trueThe label goes on its own line, immediately before the loop, and the break names it. Without the label the break would only end the inner loop, and the outer one would keep scanning the remaining rows, which is exactly what you want when you are looking for every match rather than for the first one.
When is a labeled continue useful?
A labeled continue jumps to the next pass of the labelled loop, and it skips the rest of the inner loop as well. It is the tool for "this row is finished, move on".
public class LabeledContinue {
public static void main(String[] args) {
int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
outer:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] % 2 == 0) {
continue outer;
}
System.out.println("odd value " + grid[row][col] + " at " + row + "," + col);
}
}
}
}Only two of the values printed.
odd value 1 at 0,0
odd value 7 at 2,0As soon as a row contains an even number then the whole row is abandoned, and that is why the 3 in the first row and the 5 in the second one never appear. An unlabelled continue would have skipped only the rest of the inner loop, so the row would still have been finished.
Should you use break, or return instead?
When the loop lives inside a method and the moment that you find what you are looking for is also the moment that the method is finished, then you return the value directly. It removes the flag variable and the separate break entirely.
public class FirstDivisor {
public static void main(String[] args) {
System.out.println("smallest divisor of 91: " + firstDivisor(91));
System.out.println("smallest divisor of 13: " + firstDivisor(13));
}
static int firstDivisor(int n) {
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
return d;
}
}
return n;
}
}The output shows a factor of 91 and the number itself for the prime 13.
smallest divisor of 91: 7
smallest divisor of 13: 13And notice that the loop bound uses the d * d <= n. Once the divisor passes the square root of the number then no smaller factor can exist, so the method returns the number itself when nothing was found.
What is the continue trap in a while loop?
In a while loop the continue jumps to the condition check. If the statement that advances the loop sits after the continue then it never runs and the loop spins for ever.
public class ContinueTrap {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
System.out.print(i + " ");
}
System.out.println();
}
}The output skips the 3 and carries on.
1 2 4 5And if you move the i++ below the continue then the loop never terminates. This is the single most common way to hang a Java program, and it is the reason that the advice about the continue inside the while loops is worth knowing.
Key takeaways
- The break leaves the loop immediately, and the statement after the loop still runs.
- The continue skips the rest of the current pass and it starts the next one, and the update of the for loop still happens.
- A plain break only escapes the innermost loop, and a label lets you name the loop that you actually want to leave.
- The labeled continue finishes the whole row or the iteration and it moves to the next one of the labelled loop.
- If the loop is inside a method and finding the answer ends the method then you return the value instead of breaking and returning later.
- In a while loop you make sure that the statement which advances the loop cannot be skipped by a continue.
Try it yourself: write a program that scans an array of ten numbers and reports the first number that is greater than 50, using the break, and then the index of that number, using a variable that you update before the break. Next, print every number in the array that is not a multiple of 3, using the continue. Finally, build a small 3 by 3 grid of the numbers and use a labeled break to stop the search the moment that you find a value of 7, printing the row and the column. Then remove the label and confirm that the search now continues into the following rows.