Witscale Test Center

5.4 Interrupting the loops > 5.4.2 break and continue with labels


5.4.2 break and continue with labels

We have seen that by default, the break passes the control to the first statement after the current loop and continue passes control to the next iteration. If you want the execution control to go at a particular statement after a break or continue is executed, you need to use labels in the statement. labels specify the target (statement) for the continue and the break statements. Usually only the loops statements are labeled with a label name. For example, the following loop is labeled with a label tagged followed by a colon (:)    

tagged:for (int i = 0; i < 6; i ++) {

         // do something

       }

A label name must be a valid Java identifier. The Same label names can be reused multiple times as long as they are not nested. Label names do not conflict with a variable, method or class with the same name. Therefore, you can declare a variable or method or class with the same name as label. For example, you can write the above code in a method named as tagged.

 

In general, the break and continue are unlabelled when used in programming. However, the exam expects you to know how a labeled break and continue works.

 

The table 5.5 illustrates the difference between a labeled break and continue.

 

Table 5.5 The labeled for statement with break statement and with continue statement

 

 

With break statement

With continue statement

 

 The for statement

 

outer :

    for (int i = 0; i < 5; i++) {

       for (int j = 0; j < 10; j++) {

          if (i < j) {

System.out.println("i = " + i + ", j = " + j);

              break outer;

          }

        }

        System.out.println("Just after the inner loop");

     }

     System.out.println("Just after the outer loop ");

 

outer :

    for (int i = 0; i < 5; i++) {

       for (int j = 0; j < 10; j++) {

if (i < j) {

System.out.println("i = " + i + ", j = " + j);

continue outer;

          }

        }

        System.out.println("Just after the inner loop");

     }

System.out.println("Just after the outer loop ");

Output

i = 0, j = 1

Just after the outer loop

i = 0, j = 1

i = 1, j = 2

i = 2, j = 3

i = 3, j = 4

i = 4, j = 5

Just after the outer loop

 

 

The labeled break is specified with a break keyword and label name. When a labeled break is encountered, the labeled loop is terminated. Therefore, in table 5.5, the outer loop (one with variable i) is terminated. The continue statement with label continues the iteration of the labeled for statement (one with variable i).