If you want to exit an outer loop, use break with a label:
public class Test {
public static void main(String[] args) {
s: // Label before the loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 2 && j == 2) {
break s; // Exits both loops when i = 2 and j = 2
}
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Expected Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
...
i: 1, j: 4
i: 2, j: 0
i: 2, j: 1
When i == 2 && j == 2, both loops exit using break s;.
This works only inside a loop.