Java Break
Java break statement is used to break a surrounding loop or switch statement, irrespective of the result of loop condition.
If break statement is used in nested loops, only the immediate loop is broke.
Break statement can be used inside a For loop, While loop, Do-while loop, and Switch statements.
Syntax
The syntax of break statement is
break
Examples
In the following examples, we will cover scenarios where we break different kinds of loops and switch case blocks.
Break For Loop
In the following example, we write a For loop with condition to execute until i
is less than 10. But, inside the For loop, we are conditionally breaking out of the loop when i
equals 5.
Java Program
public class Example {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4
Break While Loop
In the following example, we write a For loop with condition to execute until i
is less than 10. But, inside the For loop, we are conditionally breaking out of the loop when i
equals 5.
Java Program
public class Example {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4
Break Do-while Loop
In the following example, we write a For loop with condition to execute until i
is less than 10. But, inside the For loop, we are conditionally breaking out of the loop when i
equals 5.
Java Program
public class Example {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4
Break Switch Statement
In the following example, we write a For loop with condition to execute until i
is less than 10. But, inside the For loop, we are conditionally breaking out of the loop when i
equals 5.
Java Program
public class Example {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4