break statement in java with example

Break statement is generally used in 2 ways

  • The break statement is used to come out of the loop immediately. Whenever a break statement is written inside a loop, control comes straight out of the loop and the loop terminates for the rest of the iterations. The break statement inside the loop is used with the if statement so that the loop ends at a particular condition.

The important thing to note here is that when a break statement is used inside a nested loop, only the inner loop terminates.

  • The break statement is also used with the switch statement. Usually in a switch case a break statement is written with all the cases, whenever a break statement is encountered in the switch case block, the control comes out of the switch case body.

Syntax

break ;

Use of break statement in while loop

In the example below, we have a loop running from 0 to 100. Here we have a break statement that executes only when the value of the loop reaches 2 and on the condition The loop terminates and the control reaches the other statement of the program after the loop.

public class BreakExample1 {
public static void main(String args[],
int num =0;
while(num<=100)
,
System.out.println(“Value of variable is: “+num);
if (num==2)
,
break;
,
num++;
,
System.out.println(“Out of while-loop”);
,
,

Output

also read

Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop

Use of break statement in for loop

public class BreakExample2
,
public static void main(String args[],
,
int var;
for (var =100; var>=10; var –)
,

System.out.println(“var: “+var);
if (var==99)
,
break;
,
,
System.out.println(“Out of for-loop”);
,
,

Output

var: 100
var: 99
Out of for-loop

In the above example you can see that when the value of var is 99 then the for loop terminates.

Use of break statement in switch-case

public class BreakExample3 {

public static void main(String args[],
int num=2;

switch (num)
,
case 1:
System.out.println(“Case 1 “);
break;
case 2:
System.out.println(“Case 2 “);
break;
case 3:
System.out.println(“Case 3 “);
break;
default:
System.out.println(“Default “);
,
,
,

Output

Case 2

In this example, we have a break statement after each case block. If there is no break statement after each case block, then the statements after the case block will also be executed, in the above example the output of the same program without break is Case 2 Case 3 Default will come.

,