Control flow

The break, continue and return statements can be used to alter the flow of control within any type of loop. “break” is used to immediately terminate the enclosing loop and continue execution with the first statement occurring after the loop. “continue” is used to stop the current loop iteration, and transfer control to the end of the loop. Execution continues by incrementing the loop variable and testing to see if the loop should continue to be repeated.

Both the break and continue statements may optionally use a label to indicate the specific nested loop that the control action applies to. For example, in this nested loop the inner break statement will exit both loops as soon as the value is found:

// Search a two-dimensional array, stopping as soon as the target value is found
values = new int[][]{{1,2,3},{4,5,6});
found = false;
outer: // outer loop label
for (int i=0; i<values.length; i++) {
   for (int j=0; j<values[i].length; j++) {
      if (values[i][j] == 5) {
         found = true;
         break outer; // leave both loops
      }
   }
}

The “return” statement will exit the enclosing function context. If the return statement is processed within a loop then the return statement immediately stops loop processing, regardless of the nesting of the loops. If the function has been declared to return a value then the value must be provided with the return statement. We will look at the return statement again in the section on scripted methods.