Is there any way to break out of nested loops in Java?

Submitted 3 years, 2 months ago
Ticket #334
Views 286
Language/Framework Java
Priority Medium
Status Closed

I have tried many times but cant overcome it....

Any help would be appreciated...

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

Now I want to break out of two loops at the same time, is it possible?

Submitted on Feb 03, 21
add a comment

1 Answer

Verified

It is possible by using break Statement with labeled for loop.

public class Main {  
public static void main(String[] args) {  
            aa:  
            for(int i=1;i<=3;i++){    
                    bb:  
                    for(int j=1;j<=3;j++){    
                        if(i==2&&j==2){    
                            //using break statement with label  
                            break aa;    
                        }    
                        System.out.println(i+" "+j);    
                    }    
            }    
}  
}  

then the output will be:

1 1                                                                                                                                             
1 2                                                                                                                                             
1 3                                                                                                                                             
2 1 

Submitted 3 years, 2 months ago
sai


Latest Blogs