Break/Continue

Break

A break terminates a for loop, while loop, do while or switch statement. There are two different kinds of breaks, labeled and unlabeled. Execution continues immediately after the loop. breaks should only be used when absolutely necessary.

Unlabeled Break

An Unlabeled break terminates the innermost for loop, while loop, do while or switch statement.

for( i = 0; i < x.length; i++) {
   if(i == 6){
      break
   }
}

Labeled Break

Labeled breaks are useful for terminating an outer for loop, while loop, do while or switch statement.

loop:  for( i = 0; i < x.length; i++) {
             for( j = x.length - 1; j >= 0; j--)
               if(j== 6){
                  break loop;
               }
             }
          }

Continue

A continue skips the end of the current iteration of a for loop, while loop, do while. Execution continues at the top of the loop (with the upadate in a for loop and the condition in a while loop). Continue statements can also be labeled and unlabeled. The usage of a continue is the same as a break.

Reasons not to use Breaks/Continues

It is important to remember that breaks and continues should only be used when absolutely necessary. The reason for this is that it is always best to have only one entrance and one exit into a loop. It can be very difficult to understand code that relies on breaks and continues. It is also hard to split code that uses breaks and continues into methods.

Necessary breaks

When you are using a switch statement breaks are usually necessary otherwise everything would just fall through.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License