Java Reference
In-Depth Information
The break statement and the continue statement affect only the current loop.
If loops are nested, and a break is performed, then program flow will continue with
the next statement after the current loop. Conversely, continue will cause the cur-
rent loop to be reiterated.
for (x = 0; x < ARRAY_SIZE ; x++) {
int inputMsgSize = errorMsgs[x].msgSize;
if (inputMsgSize == 0) {
// Find the next item with some text. Then move its text into this
item's text.
for (y = x + 1; y < ARRAY_SIZE ; y++) {
inputMsgSize = errorMsgs[y].msgSize;
if (inputMsgSize != 0) {
errorMsgs[x].setErrorMsg
(errorMsgs[y].getErrorMsg);
break;
}
}
}
// The break statement causes this statement to be processed as the
next statement.
// Translate the error message.
errorMsgs[x].setErrorMsg ((errorMsgs[x].getTranslation()));
}
In this example, the break statement causes the inner for loop to be exited. The
outer loop will continue.
What happens if no error messages contain text? You would attempt to per-
form the translate method without any text! Let's hope the method is robust
enough to deal with this condition, but suppose it isn't? The best way to code for
this situation would be to break out of the outer and inner loops as soon as you dis-
cover that there is no text to translate.
Java provides a labeled break statement to help with this requirement. This
statement allows the programmer to specify which loop should be exited. It's as
close as Java gets to a goto statement. goto is not a valid Java word, but it is reserved
(that is, it is not valid as a user-defined name).
Without starting any religious arguments, it is fair to say that there are situations
where an explicit statement to exit a loop is a superior construct than complex and
hard-to-maintain if...break and if...continue statements. Once the decision is
made to exit a particular code block, it is better if the code clearly states that intention.
You can extend the example as follows:
Search WWH ::




Custom Search