← Back to Core Java Course | Chapter 4: Control Flow | Lesson 9 of 9

Java break & continue

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

java
public class Main {
	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			if (i == 3) {
				break;
			}
			System.out.println(i);
		}
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			if (i == 2) {
				continue;
			}
			System.out.println(i);
		}
	}
}

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

java
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);
			}
		}
	}
}

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

java
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);
			}
		}
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.