Let’s learn break statement in java.
Break statement in java
When break statement is encountered in a loop, it breaks the loop execution based on some condition. break statement and continue statement are two important transfer statements.
Syntax:
break;
Break statement is used to stop fall-through in switch statement. For example,
int a = 0; switch(a) { case 0: System.out.println("0"); case 1: System.out.println("1"); break; case 2: System.out.println("2"); default: System.out.println("default"); }
Output:
0
1
break statement can also be used in all types of loops namely while loop, do-while loop and for loop. Here’s how break statement works in all loops.

Let’s see an example on break statement in for loop.
public class BreakStatementExample { public static void main(String[] args) { for(int a = 1; a <= 10; a++) { if(a == 3) { // breaking loop break; } System.out.println(a); } } }
Output:
1
2
Break statement inside labeled blocks
Since JDK 1.5 we can use break statement in for loop with a label. By using this feature we can break either outer or inner loop.
public class BreakStatementForLoop { public static void main(String[] args) { aa: for(int a = 5; a <= 7; a++) { bb: for(int b = 5; b <= 7; b++) { if(a == 6 && b == 6) { // use break statement with label break aa; } System.out.println(a + " " + b); } } } }
Output:
5 5
5 6
5 7
6 5
Break statement in while loop
public class BreakStatementWhileLoop { public static void main(String[] args) { int a = 1; while(a <= 10) { if(a == 7) { a++; break;// break the loop } System.out.println(a); a++; } } }
Output:
1
2
3
4
5
6
Break statement in do-while loop
public class BreakStatementDoWhileLoop { public static void main(String[] args) { int a = 1; do { if(a == 7) { a++; break; // break the loop } System.out.println(a); a++; }while(a <= 10); } }
Output:
1
2
3
4
5
6