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]
NoLabelExampleDemp.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
packagecom.turreta.label;
publicclassNoLabelExampleDemp{
publicstaticvoidmain(String[]args){
for(inti=0;i<5;i++){
System.out.println("Outer loop: i="+i);
for(intj=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:Breakingaj=2
Outer loop:i=1
Inner loop:Breakingaj=2
Outer loop:i=2
Inner loop:Breakingaj=2
Outer loop:i=3
Inner loop:Breakingaj=2
Outer loop:i=4
Inner loop:Breakingaj=2
Done
With Labels
[wp_ad_camp_3]
On this example, we use a label named OUTER on the outer loop.
WithLabelExampleDemp.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
packagecom.turreta.label;
publicclassWithLabelExampleDemp{
publicstaticvoidmain(String[]args){
OUTER:for(inti=0;i<5;i++){
System.out.println("Outer loop: i="+i);
for(intj=0;j<5;j++){
if(j==2){
System.out.println("Inner loop: Breaking a j=2");
breakOUTER;
}
}
}
System.out.println("Done");
}
}
The codes display the following output.
Java
1
2
3
Outer loop:i=0
Inner loop:Breakingaj=2
Done
[wp_ad_camp_4]
1027 total views
, 1 views today
Got comments or suggestions?
We disabled the comments on this site to fight off spammers,
but you can still contact us via our Facebook page!.