Labeled Break and Continue
You're searching a cinema hall row by row for a free pair of seats. When you find one, you want to stop searching the whole hall, not just the current row. A plain break only ends the inner loop (the row). A labeled break names the outer loop, so you can leave both at once.
Leaving Two Loops at Once
public class FindSeat {
public static void main(String[] args) {
String[] rows = {"XXXX", "XX-X", "X--X"};
String found = "none";
search:
for (int r = 0; r < rows.length; r++) {
for (int s = 0; s < rows[r].length(); s++) {
if (rows[r].charAt(s) == '-') {
found = "row " + (r + 1) + ", seat " + (s + 1);
break search;
}
}
}
System.out.println("First free seat: " + found);
}
}First free seat: row 2, seat 3How it works
- Each string is a row:
Xis booked,-is free.charAt(s)gives the character at positions(strings get their own lessons later in the course). - Line 5 puts a label,
search:, just before the outer loop. A label is any name followed by a colon. - Line 10's
break search;ends the loop namedsearch, so both loops stop at the first free seat. - With a plain
break, only the inner loop would stop, and the outer loop would go on to check row 3.
Try it yourself: change break search; to break;. What does the program print now?
continue with a Label
continue outer; skips the rest of the outer loop's current round, including whatever is left of the inner loop:
public class FullRows {
public static void main(String[] args) {
String[] rows = {"XXXX", "XX-X", "XXXX"};
nextRow:
for (int r = 0; r < rows.length; r++) {
for (char c : rows[r].toCharArray()) {
if (c == '-') {
continue nextRow;
}
}
System.out.println("Row " + (r + 1) + " is full");
}
}
}Row 1 is full
Row 3 is fullAs soon as a free seat is found in a row, continue nextRow; moves to the next row, so the "is full" message is printed only for rows with no free seat.
Better: Use a Method
Labels work, but many teams prefer to put the search in its own method and leave it with return, which ends both loops just as well and gives the code a name. You'll write methods in "Methods in Java"; for now, know that labels are legal, occasionally handy, and rarely the only way.
Common Mistakes
Putting the label in the wrong place. The label must be directly before the loop it names. A label before a different statement gives undefined label when you use it with break or continue in a loop.
Thinking a label is goto. break label only jumps out of the labeled block; it can't jump anywhere else. goto is a reserved word that Java never uses.
Using labels everywhere. If you need several labels to follow a loop, it's time to split the code into methods.
Practice
- Easy: In a 5 × 5 multiplication table, stop printing completely as soon as a product is greater than 12, using a labeled break.
- Harder: Given rows of seats like
"XX-X", print the number of each row that has at least two free seats, usingcontinuewith a label to move on as soon as a row qualifies.
Key Takeaways
Was this tutorial helpful?