Java Break Statement
Searching your bag for your train ticket, you stop the moment you find it; you don't keep emptying the bag "to finish the loop". break gives a loop that same common sense: it ends the loop immediately, and the program carries on with the first line after it.
Stop When You Find It
public class FindPnr {
public static void main(String[] args) {
int[] pnrs = {4471, 4398, 4512, 4600, 4777};
int wanted = 4512;
int position = -1;
for (int i = 0; i < pnrs.length; i++) {
if (pnrs[i] == wanted) {
position = i;
break;
}
System.out.println("Checked " + pnrs[i]);
}
System.out.println("Found at position " + position);
}
}Checked 4471
Checked 4398
Found at position 2How it works
- The loop checks each PNR in turn.
- At position 2, the PNR matches. Line 8 saves the position, and line 9's
breakends the loop at once: line 11 doesn't run for that round, and positions 3 and 4 are never checked. - Line 13, the first line after the loop, prints the result.
positionstarts at -1, a common way to mean "not found".
Try it yourself: set wanted to 9999. What does the program print?
break in switch
In the classic switch, break stops execution from falling into the next case (see "Switch Statement"). It's the same idea: leave the enclosing block now.
break in Nested Loops
break only leaves the innermost loop it's in:
public class Rows {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int seat = 1; seat <= 5; seat++) {
if (seat == 3) {
break;
}
System.out.print("R" + row + "S" + seat + " ");
}
System.out.println("| end of row " + row);
}
}
}R1S1 R1S2 | end of row 1
R2S1 R2S2 | end of row 2
R3S1 R3S2 | end of row 3Each time seat reaches 3, the inner loop stops, but the outer loop carries on with the next row. To leave both loops at once, use a labeled break (next-but-one lesson).
Common Mistakes
Expecting break to leave an if. break isn't for if blocks; it leaves the nearest loop or switch around the if.
Expecting break to leave all nested loops. It leaves only the innermost one.
Code after break in the same block. It can never run, and the compiler reports unreachable statement.
Practice
- Easy: Loop from 1 to 100 and print the first number divisible by both 7 and 9, then stop.
- Harder: Given an array of seat statuses (
true= booked), find the first free seat and print its number (starting from 1), or "Coach full" if there's none.
Key Takeaways
Was this tutorial helpful?