public class Test {
public static void main(String[] args) {
singleLoop: for (int i = 1; i <= 5; i++) {
if (i == 3) {
break singleLoop; // Exit the loop when i equals 3
}
System.out.println(i);
}
}
}
Above is the use of break into labelled loop. labelled loops can be used if loop is in another loop
public class Test {
public static void main(String[] args) {
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Exit both loops when i equals 2 and j equals 2
}
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Leave a comment