OCA Java SE 8 Operators/Statements - Java break continue Statement








Adding Optional Labels

A label is a marker for a statement that allows the application flow to jump to it.

The label is a single word that is proceeded by a colon (:).

For example, we can add optional labels to one of the pre- vious examples:

public class Main{
   public static void main(String[] argv){
     int[][] myArray = {{5,2},{3,9},{1,7}}; 
     OUTER_LOOP:  for(int[] mySimpleArray : myArray) { 
       INNER_LOOP:  for(int i=0; i<mySimpleArray.length; i++) { 
         System.out.print(mySimpleArray[i]+"\t"); 
       } //  w w w  .  j a va 2 s  .  c om
       System.out.println(); 
     } 
   }
}

Optional labels are often only used in loop structures.

The code above generates the following result.





break Statement

A break statement transfers the flow of control out to the enclosing statement.

optionalLabel: while(booleanExpression) { 
   break optionalLabel; 
}

The break statement can take an optional label parameter.

Without a label parameter, the break statement will terminate the nearest loop.

The optional label parameter allows us to break out of a higher level outer loop.

public class Main {
  public static void main(String[] argv) {
    int[][] list = { { 11, 13, 15 }, { 11, 21, 51 }, { 21, 71, 12 } };
    int searchValue = 13;
    int x = -1;//  w ww  .  jav  a2s .  co m
    int y = -1;
    PARENT_LOOP: for (int i = 0; i < list.length; i++) {
      for (int j = 0; j < list[i].length; j++) {
        if (list[i][j] == searchValue) {
          x = i;
          y = j;
          break PARENT_LOOP;
        }
      }
    }
    System.out.println("Value " + searchValue + " found at: " + "(" + x + ","
        + y + ")");

  }
}

The code above generates the following result.





The continue Statement

The continue statement causes flow to finish the execution of the current loop.

optionalLabel: while(booleanExpression) { 
   continue optionalLabel; 
}

The continue statement transfers control to the boolean expression controlling the loop.

continue statement ends the current iteration of the loop.

The continue statement is applied to the nearest inner loop under execution and we can use optional label statements to override this behavior.

Let's take a look at the following example:

public class Main {
  public static void main(String[] argv) {
    FIRST_CHAR_LOOP: for (int a = 0; a <= 10; a++) { 
      for (char x = 'a'; x <= 'c'; x++) { 
        if (a == 5 ) 
          continue FIRST_CHAR_LOOP; 
        System.out.print(" " + a + x); 
      } /*from  w ww .  j a va  2  s. c  o  m*/
    } 
  }
}

The code above generates the following result.