how to break from multiple loops in java code example
Example 1: how to break two loop in java
import java.io.IOException;
public class BreakingFromNestedLoop{
public static void main(String args[]) throws IOException {
outer: for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i * j > 5) {
System.out.println("Breaking from nested loop");
break outer;
}
System.out.println(i + " " + j);
}
}
System.out.println("exited");
breakFromNestedLoop();
}
public static void breakFromNestedLoop(){
for(int i=0; i<6; i++){
for(int j=0; j<3; j++){
int product = i*j;
if(product > 4){
System.out.println("breaking from nested loop using return");
return;
}
}
}
System.out.println("Done");
}
}
Output
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
Breaking from nested loop
exited
breaking from nested loop using return
Example 2: java break 2 for loops
public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}