Java: Break Statement

break and continue in java

Break and Continue Statements

Sometime the programmer wants to skip some conditions in the loop or might desire to terminate the loop without evaluating the test condition. 

Break and Continue statements fulfill this same purpose.

Break statement

A break statement comes in handy when the programmer wants to skip all the statements or condition check following the break keyword. It has two primary uses:

  • When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

  • It can be used to terminate a case in the switch statement.

It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. It helps to abruptly terminate the control flow. It is compatible with all forms of loops.

Break-statement

Syntax

jump statement;

break;

Now let us proceed and understand break statement with the help of an example. We want to print a series of numbers but up to a certain limit.

The code for this purpose using for loop and break would be as follows:

Run
public class Main 
{  
    public static void main(String[] args)
    {  
        for(int i=1;i<=10;i++)
        {  
            if(i==5)
            {  
               
             break;  //using break to terminate the loop abruptly
            }  
        System.out.println(i*2);  
        }  
    }  
}

In this code we initialize a loop which runs until i <= 10. We want the loop to stop executing when i = 5.

Hence we use the break statement. Let us see what will be the output of the code above.

Output

2

4

6

8