Java 3: Control Flow, Labels & Early Returns
easy⏱ 5 mincoursejava
Labeled break & continue
Nested loops can target an outer loop with a label. outer: for (...) { for (...) { if (x) break outer; } } exits both loops at once. continue outer skips to the next iteration of the outer loop. This is the cleanest way to short-circuit a matrix scan — without labels you'd need a flag or extract the inner code into a helper that returns.
outer:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == TARGET) {
found = new int[]{ i, j };
break outer; // exits BOTH loops
}
}
}
Switch fall-through: the classic bug
Traditional switch falls through case to case unless you add break. Forgetting a break silently executes the next case — a notoriously hard-to-spot bug. Switch expressions (Java 14) use arrow syntax (case A -> ...) and don't fall through, and they can return a value. Always prefer them in new code.
// Classic switch — fall-through bug waiting to happen
switch (day) {
case MON: case TUE: case WED: case THU: case FRI:
type = "weekday"; break;
case SAT: case SUN:
type = "weekend"; break;
}
// Switch expression — Java 14+, no fall-through
String type = switch (day) {
case MON, TUE, WED, THU, FRI -> "weekday";
case SAT, SUN -> "weekend";
};
Build a matrix scanner with labeled break
Write a function findFirst(grid, target) that scans a 2D array for a target value, breaks out of both loops on match, and returns the [row, col] coordinates (or null). Count how many cells were visited — it should stop immediately on match, not scan the rest.
Prefer return over labels when extracting a helper is possible
Labels are legal but unusual — many style guides discourage them. A small helper method that returns Optional<Point> or null reads more naturally to most readers. Use labels only when the nested loop is already small and extracting would cost more clarity than the label.
Quiz: Switch expression exhaustiveness
If day is an enum, does the compiler force you to cover all cases in a switch expression? Yes — switch expressions must be exhaustive. Missing a case is a compile error. Switch statements (old style) don't enforce this.