a while loop- a do while loop
- a switch - case block.
- a specific loop marked with a label.
break - syntax
break;
break <label>
break - Example
public class Break {
public static void main(String a[]){
for(int i=1; i<=5; i++){
System.out.print("\nloop count "
+ i + ": ");
for(int j=1; j<=5; j++){
if(j>i){
break;
}
System.out.print( ""+ j + " ");
}
}
}
}
The above code would print
loop count 1: 1
loop count 2: 1 2
loop count 3: 1 2 3
loop count 4: 1 2 3 4
loop count 5: 1 2 3 4 5
Example 2:
public class BreakLabel {
public static void main(String a[]){
outer:
for(int i=1; i<=5; i++){
System.out.print("\nloop count "
+ i + ":");
for(int j=1; j<=5; j++){
if(i==3){
break outer;
}
System.out.print(""+ j + " ");
}
}
System.out.println();
for(int i=1; i<=5; i++){
System.out.print("\nloop count "
+ i + ":");
inner2:
for(int j=1; j<=5; j++){
if(i==3){
System.out.println(
"\nCalling break inner2...");
break inner2;
}
System.out.print(""+ j + " ");
}
}
}
}
This would print
loop count 1:1 2 3 4 5
loop count 2:1 2 3 4 5
loop count 3:
loop count 1:1 2 3 4 5
loop count 2:1 2 3 4 5
loop count 3:
Calling break inner2...
loop count 4:1 2 3 4 5
loop count 5:1 2 3 4 5
In the above example, 'outer' is the label. break outer is to break out of the for loop having the label 'outer'.
<<Previous
Next >>