Syntax
>>-break-+-----------------+-;->< '-LabelIdentifier-'
Description
The break statement transfers control from out of an enclosing statement.
A break statement with no label attempts to transfer control to the
innermost enclosing switch, while, do, or for
statement; this statement, which is called the break target, then completes
normally. If you have nested loops, the system starts running the next outer loop;
otherwise, the program continues executing the next statement after the loop. If you do
not enclose the break statement with a switch, while,
do, or for statement, a compilation error occurs.
A break statement with a label attempts to transfer control to the enclosing
labeled statement that has the same identifier as its label; this statement, the
break target, then completes normally. In this case, the break target need not be a switch,
while, do, or for statement. If you do not
enclose the break statement with a labeled statement with the same identifier as its
label, a compilation error occurs.
The preceding descriptions say "attempts to transfer control" rather than just
"transfers control" because if there are any try statements within
the break target whose try blocks contain the break statement,
then any finally clauses of those try statements are executed,
in order, innermost to outermost, before control is transferred to the break target.
Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break
statement.
Example
The following is a simple example showing how to break out of nested for
loops.
boolean brokeOut = false; for (int i = 0; i < MAX_ITERATIONS; i++) { // the outer for loop for (int j = 0; j < i; j++) { // the inner for loop if ((i*j) == BREAK_VALUE) { brokeOut = true; break; // break out of the inner for loop } } if (brokeOut) { // this is first place we break to break; // break out of the outer for loop } } theIntVar = 10; // this is the second place we break to
Syntax diagrams
Labeled statements
do keyword
for keyword
switch keyword
while keyword
Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.