Break and continue statement

  • Eclipse: Oxygen
  • Java: 1.8

In this tutorial, we will discuss the Break and Continue statement. Before knowing the continue instruction, let’s define the break instruction.

Break statement

Sometimes it is required to do terminate the loop, without verifying test expression. In such cases break statement can be used. The break statement normally used with the conditional switch statement and do, while or for loop statement. The break statement transfers the flow of control out of the current scope.

How break statement works

Program: Demonstration of break statement

we have for loop running from 1 to 10, but we have a break statement applied when the loop value equals to 5, the loop will get terminated and control will come out of the loop body and get passes to next statement in the program.

Output:

1

2

3

4

5

Continue statements

Sometimes if the programmer wants to skip a few statements inside the loop. In such cases, continue statements are used. Generally, the continue statement ends the current iteration of the loop.

How to continue statement works

Program: Demonstration of the continue statement

In the following statement, we have for loop running from 1 to 10, we can observe that we have skipped println statement for number 5. Why? Because when the value of variable i==5, Java skips post continue statements for the particular iteration in a loop. Which makes it to jump at the beginning of for loop for the next iteration and skipping the current iteration.

Output:

1

2

3

4

6

7

8

9

10

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu