Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to break out of nested for loops in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        outer: for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i + j > 5) {
                    System.out.println("break");
                    System.out.println(i + " : " + j);
                    break outer;
                }
                System.out.println(i + " : " + j);
            }

        }
        System.out.println("end nested for loop");
    }
}
    
    
    
    
/*
run:
    
0 : 0
0 : 1
0 : 2
0 : 3
0 : 4
1 : 0
1 : 1
1 : 2
1 : 3
1 : 4
2 : 0
2 : 1
2 : 2
2 : 3
break
2 : 4
end nested for loop
    
*/

 



answered Nov 7, 2021 by avibootz
0 votes
public class MyClass {
    public static void breakFromNestedForLoop() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i + j > 5) {
                    System.out.println("return == break");
                    System.out.println(i + " : " + j);
                    return;
                }
                System.out.println(i + " : " + j);
            }

        }
        System.out.println("end nested for loop");
    }
    public static void main(String args[]) {
        breakFromNestedForLoop();
    }
}
    
    
    
    
/*
run:
    
0 : 0
0 : 1
0 : 2
0 : 3
0 : 4
1 : 0
1 : 1
1 : 2
1 : 3
1 : 4
2 : 0
2 : 1
2 : 2
2 : 3
return == break
2 : 4
    
*/

 



answered Nov 7, 2021 by avibootz
edited Nov 7, 2021 by avibootz

Related questions

1 answer 306 views
3 answers 318 views
3 answers 285 views
3 answers 300 views
2 answers 272 views
4 answers 364 views
3 answers 310 views
310 views asked Sep 7, 2022 by avibootz
...