Example Label, Break, Continue With Java
Example Label, Break, Continue With Java
class BreakLabelDemo {
public static void main(String args[])
{
boolean t = true;
first : {
second : {
third : {
System.out.println("Before the break statement");
// if (t) break second;
System.out.println("This won't execute.");
} //third
System.out.println("This won't execute.");
} //second
System.out.println("This is after second block.");
} //first
}
}
Output:
Before the break statement.
This is after the second block.
1. public class BreakExample3 {
2. public static void main(String[] args) {
3. aa:
4. for(int i=1;i<=3;i++){
5. bb:
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. //using break statement with label
9. break aa;
10. }
11. System.out.println(i+" "+j);
12. }
13. }
14. }
15. }
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the
default behavior of any loop
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Continue Statement with Inner Loop
Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
Java Continue Statement with Labeled For Loop
1. public class ContinueExample3 {
2. public static void main(String[] args) {
3. aa:
4. for(int i=1;i<=3;i++){
5. bb:
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. //using continue statement with label
9. continue aa;
10. }
11. System.out.println(i+" "+j);
12. }
13. }
14. }
15. }
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3