Java Reference
In-Depth Information
Note that a labeled
break
is not a
goto
. The
goto
statement would enable
indiscriminate jumping around in code, obfuscating the flow of control. A
break
or
continue
that references a label, on the other hand, exits from or
repeats only that specific labeled block, and the flow of control is obvi-
ous by inspection. For example, here is a modified version of
workOnFlag
that labels a block instead of a loop, allowing us to dispense with the
found
flag altogether:
public boolean workOnFlag(float flag) {
int y, x;
search:
{
for (y = 0; y < matrix.length; y++) {
for (x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] == flag)
break search;
}
}
// if we get here we didn't find it
return false;
}
// do some stuff with flagged value at matrix[y][x]
return true;
}
You should use the
break
statement judiciously, and with thought to the
clarity of the resulting code. Arbitrarily jumping out of loops or state-
ments can obscure the flow of control in the code, making it harder
to understand and maintain. Some programming styles ban the use of
break
altogether, but that is an extreme position. Contorting the logic in
a loop to avoid the need for a
break
can result in code that is less clear
than it would have been with the
break
.