Break Statement In Java with Examples
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