The break statement
The java break statement is used to break the flow of control in the program. It can be used with loops and with a switch case statement only.
Syntax
The syntax of the break statement is very simple-
break;
Break statement with loop
The break statement can be used with any type of loop like – for loop, while loop, do while loop. Java provides two different ways to use the break statement inside a loop –
- Normal break statement
- Labeled break statement
Normal break statement
The normal break statement is the simplest form of break statement following is the example of a normal break statement –
Example
public class NormalBreak { public static void main(String[] args) { int num = 5; for(int i = 0; i < 10; i++) { System.out.println(i); if(i == num) { // Break the loop break; } } } }
Explanation
In the above example program, one loop is started from 0 to 9, and inside the body of the loop, we are checking if the value of the variable (i) equals to the value of the variable (num) then break the loop. So whenever the condition i == num becomes true, the break statement executes and it terminates and stops the further execution of the loop and control comes outside of the loop.
Labeled break statement
The labeled break statement is used when we have nested looping and we want to target a particular loop to stop. Following is the example of a labeled break statement –
Example
public class Main { public static void main(String[] args) { outer: for(int i = 0; i < 4; i++) { inner: for(int j = 0; j < 4; j ++ ) { if (i == 2) { // Break the outer loop break outer; } System.out.println("i = " + i + " j = " +j); } } } }
Explanation
In the above example program, we have labeled the loop, the nested loop is labeled as inner: and the outer loop is labeled as outer: we will be using these labeling to identify and stop the loop. Now in the nested loop, we are checking if the value of the variable (i) equals 2 then execute the break statement but this time we are telling the break statement to break the given labeled loop, so instead of the current loop, it breaks the outer loop.
Break statement with switch case
See how to use break statement with switch case – Java switch case