Java Reference
In-Depth Information
FIGURE 3.7
The syntax of a
break
statement.
When using a label, a colon is required.
optional_label
: while (
boolean_expression
) {
//anywhere within the loop:
break
optional_label
;
}
When the break statement
executes, control immediately
jumps to the next statement
following the control structure.
We saw an example of using an unlabeled
break
in the earlier section on
switch
statements. A break statement within one of the repetition control structures causes the
loop to immediately complete. For example, see if you can determine the effect of the
break
in this loop:
3. for(int k = 1; k < 10; k++) {
4. System.out.print(k + “ “);
5. if(k % 3 == 0)
6. break;
7. }
If the loop control variable
k
is divisible by
3
on line 5, then the break executes on line 6
and fl ow of control jumps down to the next statement after line 7. The output of this loop is
1 2 3
Let's look at a more complex example. The following
Vacation
class uses an enhanced
for
loop to iterate over an enum named
Days
. Examine the code and see if you can
determine the output of running
main
:
1. public class Vacation {
2. public enum Days {
3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
4. THURSDAY, FRIDAY, SATURDAY
5. }
6.
7. public void workUntil(Days dayOff) {
8. for(Days day : Days.values()) {
9. if(day != dayOff) {
Search WWH ::
Custom Search