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 231 views
3 answers 235 views
3 answers 195 views
3 answers 205 views
2 answers 197 views
4 answers 263 views
3 answers 215 views
215 views asked Sep 7, 2022 by avibootz
...