Breaking Loops
There are two kinds of breaks for a loop:- The unlabeled break:
break;
- The labeled break:
break label;
What you must know about the unlabeled break is:
- It terminates the innermost
switch
,for
,while
, ordo-while
- You get a compiler error if not one of these loops encloses the
break
statement
And what you must know about the labeled break is:
- It terminates the labeled statement (any, not only loops)
- The control flow is transferred to the statement immediately following the labeled (terminated) statement or block
- It’s valid only within the block of code under the scope of the label
Below you have a couple of labeled break examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Example 1: break a block block : { // … code here break block; // … more code here } next_statement_after_break; // Example 2: break nested statements label1: for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { if (i == j) { break label1; } } } next_statement_after_break; |
Finally, remember that you can also break the execution flow using the return
reserved word to exit from the current method: return;
for void methods or return expression;
for non-void methods.
Continuing Loops
There are also two ways to continue (skip the current iteration) a loop:- The unlabeled continue:
continue;
- The labeled continue:
continue label;
What you must know about the unlabeled continue is:
- It skips the current iteration of a
for
,while
, ordo-while
loop - It skips to the end of the innermost loop’s body and evaluates the boolean expression that controls the loop
- You get a compile-time error if either:
- No
for
,while
ordo
statement encloses thecontinue
- The
continue
target (label) is not afor
,while
ordo
- No
And what you must know about the labeled continue is that it’s exactly as the unlabeled one (same considerations) but in this case it skips the current iteration of an outer loop marked with the given label.
Below you have a couple of continue
examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Example 1: unlabeled continue (it prints 1 and 2) for (int i = 0; i < 3; i++) { if (i == 0) continue; else System.out.println(i); } // Example 2: labeled continue (it prints nothing) label1: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 0) continue label1; else System.out.println(j); } } |