In Java, the break
statement is used for three purposes. First, it cancels a statement sequence in a switch
statement. Second, it can be used to end a loop. Lastly, it can be used as a “civilized” form of goto. The last two uses are described here.
Using the Break to Exit a Loop in Java
With the use of break
, you can force instant termination of a loop, bypassing the conditional expression and any residual code in the body of the loop. When a break
statement is met inside a loop, the loop is terminated, and program control resumes at the next statement following the loop. Here is a simple illustration:
// Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }
This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete.
As you can notice, although the for
loop is created to run from 0 to 99, the break
statement makes it terminate early, when i
equals 10.
The break
statement can be employed with any of Java’s loops, including intentionally infinite loops. For instance, here is the other program coded by use of a while
loop. The result of this program is the same as just explained.
// Using break to exit a while loop. class BreakLoop2 { public static void main(String args[]) { int i = 0; while(i < 100) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } }
When used inside a set of nested
loops, the break
statement will only break out of the
innermost loop. For instance:
// Using break with nested loops. class BreakLoop3 { public static void main(String args[]) { for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops complete."); } }
This program generates the following output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete.
As you can observe, the break
statement in the inner loop only causes termination of that loop. The outer loop is unchanged.
Here are two more points to remember about break
. First, more than one break
statement may appear in a loop. However, be careful. Too many break
statements tend to restructure your code. Second, the break
that terminates a switch
statement affects only that switch
statement and not any enclosing loops.
Using break as a Form of Goto
In summation to its uses with the switch
statement and loops, the break
statement can also be used by itself to provide a “civilized” form of the goto statement. Java does not contain a goto statement as it gives way to branch in an arbitrary and unstructured manner. This usually makes goto-ridden
code hard to understand and hard to manage. It also prevents specific compiler optimizations.
There are, however, some places where the goto is a relevant and legitimate construct for flow control. For instance, the goto can be helpful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break
statement. By using this form of break
, you can, for instance, break
out of one or more blocks of code.
These blocks does not need to be a part of a loop or a switch
. They can be any block. Moreover, you can define precisely where execution will resume, because this form of break
works with a label. As you will see, break
gives you the advantages of a goto without its problems.
The usual form of the labeled break statement is given here:
break label;
Usually, label
is the name of a label that recognizes a block of code. This can be a stand-alone block of code, but it can also be a block that is the target of another statement. When this form of break
executes, control is transferred out of the named block. The labeled block must enclose the break
statement, but it does not need to be the immediately enclosing block.
This means, for instance, that you can use a labeled break
statement to exit from a set of nested blocks. But you cannot use break
to shift control out of a block that does not enclose the break statement.
To name a block, put a label at the start of it. A label
is any logical Java identifier followed by a colon. Once you have labeled a block, you can then use this label as the target of a break
statement. Doing so makes execution to resume at the end of the labeled block.
For instance, the following program shows three nested blocks, each with its label. The break
statement causes execution to jump forward, past the end of the block labeled second, skipping the two println( )
statements.
// Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } }
Running this program generates the following output:
Before the break. This is after second block.
One of the most general uses for a labeled break
statement is to exit from nested loops. For instance, in the next program, the outer loop executes only once:
// Using break to exit from nested loops class BreakLoop4 { public static void main(String args[]) { outer: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break outer; // exit both loops System.out.print(j + " "); } System.out.println("This will not print"); } System.out.println("Loops complete."); } }
This program generates the following output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
As you can notice, when the inner loop breaks to the outer loop, both loops have been terminated. See that this illustration labels for a statement, which has a block of code as its target.
Keep in mind that you cannot break
to any label which is not defined for an enclosing block. For example, the following program is invalid and will not compile:
// This program contains an error. class BreakErr { public static void main(String args[]) { one: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); } for(int j=0; j<100; j++) { if(j == 10) break one; // WRONG System.out.print(j + " "); } } }
Since the loop labeled one does not enclose the break
statement, it is not possible to transfer control out of that block.