The Break statement in Java is used to break a loop statement or switch statement. The Break statement breaks the current flow at a specified condition.
Note: In case of inner loop, it breaks just the inner loop.
Syntax:
break;
Break Statement Sample Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package ClassThreeControlFlowStatements; public class BreakStatement { public static void main(String[] args) { for (int i=1; i<=10; i++) { if (i==4) { break; } System.out.println("Value of i is "+i); } } } |
Break Statement within Switch Case:
Refer Switch Case Statement.
Break Statement with inner loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package ClassThreeControlFlowStatements; public class BreakStatementInnerLoop { public static void main(String[] args) { for (int x=1; x<=4; x++) { for (int y=1; y<=4; y++){ if (x==2 && y==2) { System.out.println("Value of x is "+x+" and Value of y is "+y); break; } System.out.print(x); System.out.println(y); } } } } |
Must Read: Java Tutorial