Java Break statement
The flow of the code will immediately be terminated whenever a break statement is encountered within a loop and resumes control at the next statement to the loop block. The break statement will break the flow of the program at a given condition.
If you mentioned the break statement within the inner loop then the control comes out of the inner loop only. Break statement works with all type of loop statements.
Syntax-
jump-statement;
break;
-
Break statement with the for-loop
Example-
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=5;i++){
if(i==4){
break;
}
System.out.println(i);
}
}
}
Output-
1
2
3
-
Break statement with the inner loop
Example-
public class Example2 {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
System.out.println(i+" "+j);
}
}
}
}
Output-
1 1
1 2
1 3
2 1
3 1
3 2
3 3
-
Break statement with a while loop
Example-
public class BreakWhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
if(i==5){
i++;
break;
}
System.out.println(i);
i++;
}
}
}
Output-
1
2
3
4
-
Break statement with a do-while loop
Example-
public class BreakDoWhileExample {
public static void main(String[] args) {
int i=1;
do{
if(i==5){
i++;
break;
}
System.out.println(i);
i++;
}while(i<=10);
}
}
Output-
1
2
3
4