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, or do-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:

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, or do-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 or do statement encloses the continue
    • The continue target (label) is not a for, while or do

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:

 


Leave a Reply