Careeroza
break and continue
break
Example
break exits the loop immediately.
public class Main {
public static void main(String[] args) {
int[] orderIds = {101, 205, 309, 412, 518};
int target = 309;
for (int i = 0; i < orderIds.length; i++) {
System.out.println("Checking " + orderIds[i]);
if (orderIds[i] == target) {
System.out.println("Found at position " + i);
break;
}
}
}
}Output
Checking 101 Checking 205 Checking 309 Found at position 2
continue
Example
continue skips the rest of the current round and moves to the next one.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
System.out.print(i + " ");
}
System.out.println();
}
}Output
1 2 4 5 7 8 10
Labeled break
Example
A plain break leaves only the innermost loop. A label lets you leave an outer loop.
public class Main {
public static void main(String[] args) {
int[][] seats = {{0, 0, 1}, {1, 0, 0}, {0, 1, 0}}; // 0 = free
search:
for (int row = 0; row < seats.length; row++) {
for (int col = 0; col < seats[row].length; col++) {
if (seats[row][col] == 1) {
System.out.println("First booked seat: row " + row + ", col " + col);
break search;
}
}
}
}
}Output
First booked seat: row 0, col 2