Break statement can use in looping statement (for,while,do while) and also in switch case.
Break statement is used to terminate the execution of the current loop or current switch.
Break statement is also used to the execution of label.
Break statement is used in two variation
1. Break
2. Break label
1. Break
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class LoopBreaker { public static void main(String[] s) { for (int i = 1; i <= 10; i++) { System.out.println("value of i=" + i); if (i == 5) { System.out.println("breaking this look for i=" + i); break; } } System.out.println("outside loop"); } } |
Result
1 2 3 4 5 6 7 | value of i=1 value of i=2 value of i=3 value of i=4 value of i=5 breaking this look for i=5 outside loop |
2. Break with label
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class LoopLabelExample { public static void main(String[] s) { loop: for (int i = i = 1; i <= 10; i++) { for (int j = 1; j <= i; j++) { if (i == 3) { break loop; } System.out.println("value of i = " + i + " value of j = " + j); } } System.out.println("outside loop"); } } |
Result
1 2 3 4 | value of i = 1 value of j = 1 value of i = 2 value of j = 1 value of i = 2 value of j = 2 outside loop |