Java break and continue
break and continue change the normal flow of a loop.
break
break stops the loop at once.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
System.out.println("Loop ended");
}
}
Output
1
2
3
4
Loop ended
continue
continue skips the rest of the current round and goes to the next round.
public class Skip {
public static void main(String[] args) {
for (int i = 1; i <= 8; i++) {
if (i % 2 == 0) {
continue; // skip the even numbers
}
System.out.print(i + " ");
}
System.out.println();
}
}
Output
1 3 5 7
Search with break
public class Search {
public static void main(String[] args) {
int[] numbers = {4, 9, 15, 22, 31};
int target = 15;
int found = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
found = i;
break; // no need to check the others
}
}
System.out.println("Found at index " + found);
}
}
Output
Found at index 2
Labeled break for nested loops
A plain break only leaves the inner loop. To leave the outer loop too, give it a label:
public class Label {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j == 4) {
System.out.println("Found at i=" + i + ", j=" + j);
break outer;
}
System.out.println(i + " x " + j + " = " + (i * j));
}
}
System.out.println("Done");
}
}
Output
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
Found at i=2, j=2
Done
You can use continue outer; in the same way, to go to the next round of the outer loop.
Note:
Too many break and continue make loops hard to read. When it is possible, write a clear condition instead. Next: Java Arrays.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |