Java Reference
In-Depth Information
As you can see, the break statement in the inner loop causes the termination of only that
loop. The outer loop is unaffected.
Here are two other points to remember about break . First, more than one break state-
ment may appear in a loop. However, be careful. Too many break statements have the
tendency to destructure your code. Second, the break that terminates a switch statement
affects only that switch statement and not any enclosing loops.
Use break as a Form of goto
In addition to its uses with the switch statement and loops, the break statement can be em-
ployed by itself to provide a “civilized” form of the goto statement. Java does not have a
goto statement, because it provides an unstructured way to alter the flow of program ex-
ecution. Programs that make extensive use of the goto are usually hard to understand and
hard to maintain. There are, however, a few places where the goto is a useful and legitim-
ate device. For example, the goto can be helpful when 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 example, break out of one or more blocks of code.
These blocks need not be part of a loop or a switch . They can be any block. Further, you
can specify precisely where execution will resume, because this form of break works with
a label. As you will see, break gives you the benefits of a goto without its problems.
The general form of the labeled break statement is shown here:
break label ;
Typically, label is the name of a label that identifies a block of code. When this form of
break executes, control is transferred out of the named block of code. The labeled block
of code must enclose the break statement, but it does not need to be the immediately en-
closing block. This means that you can use a labeled break statement to exit from a set of
nested blocks. But you cannot use break to transfer control to a block of code that does not
enclose the break statement.
Search WWH ::




Custom Search