break, continue & Nested Loops
Sometimes you need to leave a loop early, skip one repetition, or loop inside another loop to work with grids and combinations. break, continue and labels give you that control.
break: leave the loop
void main() { int[] values = {3, 8, -1, 12, 7}; for (int v : values) { if (v < 0) { System.out.println("Found a negative value, stopping."); break; } System.out.println("Processing " + v); } }
Processing 3 Processing 8 Found a negative value, stopping.
Searching with break
void main() { String[] names = {"Lucas", "Sofia", "Mei", "Jonas"}; int found = -1; for (int i = 0; i < names.length; i++) { if (names[i].equals("Mei")) { found = i; break; } } System.out.println(found >= 0 ? "Mei is at index " + found : "Not found"); }
Mei is at index 2
Once you've found what you're looking for, there's no point checking the rest.
continue: skip to the next repetition
void main() { 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
continue skips the rest of the body and moves straight to the next repetition. It's useful for ignoring items that don't apply, keeping the main logic un-nested.
Nested loops
void main() { for (int row = 1; row <= 4; row++) { for (int col = 1; col <= row; col++) { System.out.print("*"); } System.out.println(); } }
* ** *** ****
The inner loop runs completely for every repetition of the outer loop. Nested loops are how you work with grids, tables, pairs and combinations.
All pairs
void main() { String[] players = {"Ana", "Ben", "Chloé", "David"}; int matches = 0; for (int i = 0; i < players.length; i++) { for (int j = i + 1; j < players.length; j++) { System.out.println(players[i] + " vs " + players[j]); matches++; } } System.out.println(matches + " matches"); }
Ana vs Ben Ana vs Chloé Ana vs David Ben vs Chloé Ben vs David Chloé vs David 6 matches
Starting the inner loop at i + 1 avoids pairing a player with themself and listing each pair twice. Watch the cost: nested loops over n items take about n² steps, which grows quickly.
Labelled break and continue
void main() { int[][] grid = { {1, 2, 3}, {4, 99, 6}, {7, 8, 9} }; search: for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] == 99) { System.out.println("Found 99 at row " + r + ", column " + c); break search; } } } }
Found 99 at row 1, column 1
A plain break only exits the innermost loop. A label (search:) names an outer loop so break search leaves both at once. Labels are rare; often moving the loops into a method and using return is clearer.
Try it yourself
Print all prime numbers below 50, using continue on the outer loop when a divisor is found.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47