1import java.io.IOException;
2
3/**
4 * How to break from nested loop in Java. You can use labeled
5 * statement with break statement to break from nested loop.
6 *
7 * @author WINDOWS 8
8 */
9
10public class BreakingFromNestedLoop{
11
12 public static void main(String args[]) throws IOException {
13
14 // this is our outer loop
15 outer: for (int i = 0; i < 4; i++) {
16
17 // this is the inner loop
18 for (int j = 0; j < 4; j++) {
19
20 // condition to break from nested loop
21 if (i * j > 5) {
22 System.out.println("Breaking from nested loop");
23 break outer;
24 }
25
26 System.out.println(i + " " + j);
27 }
28
29 }
30 System.out.println("exited");
31
32
33
34 // better way is to encapsulate nested loop in a method
35 // and use return to break from outer loop
36 breakFromNestedLoop();
37
38 }
39
40 /**
41 * You can use return statement to return at any point from a method.
42 * This will help you to break from nested loop as well
43 */
44 public static void breakFromNestedLoop(){
45 for(int i=0; i<6; i++){
46
47 for(int j=0; j<3; j++){
48 int product = i*j;
49
50 if(product > 4){
51 System.out.println("breaking from nested loop using return");
52 return;
53 }
54 }
55 }
56 System.out.println("Done");
57 }
58
59}
60
61Output
620 0
630 1
640 2
650 3
661 0
671 1
681 2
691 3
702 0
712 1
722 2
73Breaking from nested loop
74exited
75breaking from nested loop using return