Java break & continue
In this page:
The break Statement
break exits its enclosing loop immediately, skipping any remaining iterations entirely and jumping straight to the first statement after the loop's closing brace.
Example: The break Statement
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
The continue Statement
continue skips only the rest of the current iteration's code, then jumps straight to the loop's next condition check or update step -- unlike break, the loop itself keeps running afterward.
Example: The continue Statement
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Labeled break
A labeled break (like outer: for (...) { for (...) { break outer; } }) lets code inside a nested inner loop terminate a specific outer loop directly, which a plain break -- which only affects its immediate loop -- can't do.
Example: Labeled break
public class Main {
public static void main(String[] args) {
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break outer;
}
System.out.println(i + "," + j);
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Labeled continue
A labeled continue works the same way but skips to the next iteration of the named outer loop rather than the inner one, letting you abandon the current inner-loop pass and resume the outer loop's cycle.
Example: Labeled continue
public class Main {
public static void main(String[] args) {
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
continue outer;
}
System.out.println(i + "," + j);
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
break in switch-case
Inside a switch-case, break stops execution from falling through into the next case block -- functionally similar to how it exits a loop, but here it's exiting the switch statement instead.
Example: break in switch-case
public class Main {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: