Java Break and Continue
Sometimes a loop should not run all its rounds. When you find what you were looking for, there is no need to keep searching. When one item is not interesting, you want to skip it and go on. Java gives you two statements for this: break and continue. They work in every loop you have seen: while, do while and for.
break: leave the loop
break ends the loop immediately. The program continues with the first statement after the loop:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
System.out.println("Stopped early.");
}
}1 2 3 4 Stopped early.
A typical use is searching: stop as soon as you have found the answer. This loop finds the first number above 100 that is divisible by 7:
public class Main {
public static void main(String[] args) {
int n = 101;
while (true) {
if (n % 7 == 0) {
break;
}
n++;
}
System.out.println("First multiple of 7 above 100: " + n);
}
}First multiple of 7 above 100: 105
while (true) looks like an endless loop, but the break inside ends it. This pattern is common when the exit condition is easiest to check in the middle of the loop.
continue: skip to the next round
continue skips the rest of the current round and goes straight to the next one. In a for loop the step (i++) still runs:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue;
}
System.out.print(i + " ");
}
System.out.println();
}
}1 2 4 5 7 8 10
The multiples of 3 are skipped. In a while loop, be careful: if the counter is changed after the continue, it is skipped too, and the loop may never end.
Loops in loops and labels
A break only leaves the innermost loop. To leave an outer loop from inside an inner one, give the outer loop a label (a name followed by a colon) and write break label;:
public class Main {
public static void main(String[] args) {
search:
for (int a = 1; a <= 9; a++) {
for (int b = 1; b <= 9; b++) {
if (a * b == 42) {
System.out.println(a + " x " + b + " = 42");
break search;
}
}
}
System.out.println("Search finished.");
}
}6 x 7 = 42 Search finished.
Without the label, only the inner loop would stop, and the outer loop would find 7 x 6 as well. Labels are rarely needed; often a method with return is a cleaner way out.
Practice exercises
- Print the numbers from 1 to 20 but stop as soon as you reach a number divisible by both 3 and 4.
- Print the numbers from 1 to 15, skipping the even ones with
continue. - Find the first two-digit number whose digits add up to 12.