How do I break out of nested loops in Java?
To break out of nested loops in Java, you can use the break
statement. The break
statement terminates the innermost loop that it is contained in, and transfers control to the statement immediately following the loop.
Here's an example of how you can use the break
statement to break out of nested loops:
public class Main {
public static void main(String[] args) {
// Outer loop
outer:
for (int i = 1; i <= 3; i++) {
// Inner loop
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// Break out of both loops
break outer;
}
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
This code will print the following output:
i = 1, j = 1 i = 1, j = 2 i = 1, j = 3
The break
statement terminates the inner loop when i
is equal to 2 and j
is equal to 2, and transfers control to the statement following the outer loop.
Alternatively, you can use the labeled break
statement to specify which loop you want to break out of. To use a labeled break, you can add a label before the loop, and then use the break
statement followed by the label to break out of the loop. In the example above, the label outer
is used to identify the outer loop, and the break outer
statement is used to break out of the outer loop.
Note that the break
statement can only be used to break out of loops, and not other control structures such as if
statements or switch
statements. To break out of these structures, you can use the return
statement instead.