[wp_ad_camp_1]
Whenever you use break;
(or continue;
), by default it only affects the current loop where it is invoked . If you are in a inner loop, surely the only loop that you can break;
from is that loop. What if you need to break;
from the outer-most loop in order to proceed to the next set of instructions?
We use Optional Labels.
No Labels
On this example, we are not using any labels and breaking from the inner loop.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.turreta.label; public class NoLabelExampleDemp { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println("Outer loop: i=" + i); for (int j = 0; j < 5; j++) { if (j == 2) { System.out.println("Inner loop: Breaking a j=2"); break; } } } System.out.println("Done"); } } |
The codes display the following output.
1 2 3 4 5 6 7 8 9 10 11 | Outer loop: i=0 Inner loop: Breaking a j=2 Outer loop: i=1 Inner loop: Breaking a j=2 Outer loop: i=2 Inner loop: Breaking a j=2 Outer loop: i=3 Inner loop: Breaking a j=2 Outer loop: i=4 Inner loop: Breaking a j=2 Done |
With Labels
[wp_ad_camp_3]
On this example, we use a label named OUTER
on the outer loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.turreta.label; public class WithLabelExampleDemp { public static void main(String[] args) { OUTER: for (int i = 0; i < 5; i++) { System.out.println("Outer loop: i=" + i); for (int j = 0; j < 5; j++) { if (j == 2) { System.out.println("Inner loop: Breaking a j=2"); break OUTER; } } } System.out.println("Done"); } } |
The codes display the following output.
1 2 3 | Outer loop: i=0 Inner loop: Breaking a j=2 Done |
[wp_ad_camp_4]