Witscale Test Center

5.4 Interrupting the loops > 5.4.1 break and continue


5.4.1 break and continue

The break and continue can be used in any of three iterative statements, while, do-while or for. Table 5.4 demonstrates the difference between the break and the continue statement. The break statement used within the for loop’s body breaks the execution of the current for loop and transfers the control out of the loop. The continue statement on the other hand, terminates the execution of the current iteration and transfers the control to the loop. So it continues the execution to the next iteration.

 

 

Table 5.4 The for statement with the break statement and with the continue statement

 

 

With break statement

With continue statement

 

 for statement

for (int i = 1; i <= 10; i++) {

  if (i % 3 == 0) {

System.out.println("Number divisible by 3 in 1-10 is " + i);

     break;

  }

}

 

For (int i =1; i <= 10; i++) {

  if (i % 3 == 0) {

System.out.println("Number divisible by 3 in 1-10 is " + i);

    Continue;

  }

}

Output

Number divisible by 3 in 1-10 is 3

Number divisible by 3 in 1-10 is 3

Number divisible by 3 in 1-10 is 6

Number divisible by 3 in 1-10 is 9

 

 

The working of break and continue is simpler to understand in single loop. But the break statement can be confusing in the case of nested loops.  For them, the rule of thumb is that the break statement passes the control to the immediate outer loop. However, this may not always be desirable. For instance, if there are three loops nested within each other and if you want the control to be passed to a specific loop, you need to label the loops. In the next section, we’ll see how we can use labels to specify where the control is passed.