When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
Flowchart of Break Statement
Java Break Statement with Loop
Example:
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Example:
//Java Program to illustrate the use of break statement
//inside an inner loop
public class BreakExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement inside the inner loop
break;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Break Statement with Labeled For Loop
We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer or inner loop.
Example:
//Java Program to illustrate the use of continue statement
//with label inside an inner loop to break outer loop
public class BreakExample3 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement with label
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
Java Break Statement in while loop
Example:
//Java Program to demonstrate the use of break statement
//inside the while loop.
public class BreakWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
Java Break Statement in do-while loop
Example:
BreakDoWhileExample.java
//Java Program to demonstrate the use of break statement
//inside the Java do-while loop.
public class BreakDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
Leave a Reply