In Java, any statement can be given a label
(a name followed by a colon). However, it is only useful to label loops
and switch statements.
A break statement typically takes
control out of the innermost loop or switch statement. However,
it can also specify the label of any enclosing labeled loop or switch
statement, to cause that statement to exit. For example:
boolean containsZero = false;
zeroCheck:
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
if (myArray[i][j] == 0) {
containsZero = true;
break zeroCheck;
}
}
}
|
A continue statement typically
takes returns control to the test part of the innermost enclosing loop
statement. However, it can specify the label of any enclosing loop, to
take control to the test part of that loop.
Use labels only as a last resort, after exploring other possible means of writing
the code. For example, the above code could be better written as a call to the
following method:
boolean containsZero(int[][] myArray) {
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
if (myArray[i][j] == 0) return true;
}
}
return false;
} |