Java Reference
In-Depth Information
255
In general, a
break
is a very poor way of exiting a loop. In 1990, a misused
break
caused an AT&T 4ESS telephone switch to fail, and the failure propagated
through the entire U.S. network, rendering it nearly unusable for about nine hours.
A programmer had used a
break
to terminate an
if
statement. Unfortunately,
break
cannot be used with
if
, so the program execution broke out of the
enclosing
switch
statement, skipping some variable initializations and running
into chaos [2, p. 38]. Using
break
statements also makes it difficult to use
correctness proof techniques (see
Advanced Topic 6.5
).
However, when faced with the bother of introducing a separate loop control
variable, some programmers find that
break
statements are beneficial in the
Ȓloop and a halfȓ case. This issue is often the topic of heated (and quite
unproductive) debate. In this topic, we won't use the
break
statement, and we
leave it to you to decide whether you like to use it in your own programs.
In Java, there is a second form of the
break
statement that is used to break out of
a nested statement. The statement
break
label; immediately jumps to the end of
the statement that is tagged with a label. Any statement (including
if
and block
statements) can be tagged with a labelȌthe syntax is
label: statement
The labeled
break
statement was invented to break out of a set of nested loops.
outerloop:
while
(outer loop condition)
{ . . .
while
(inner loop condition)
{ . . .
if
(something really bad happened)
break outerloop;
}
}
Jumps here if something really bad happened
Naturally, this situation is quite rare. We recommend that you try to introduce
additional methods instead of using complicated nested loops.