Menu

Java Break and Continue in Loops

These two keywords help us control the loop from within it. break will cause the loop to stop and will go immediately to the next statement after the loop:

int i;
for (i = 0; i < 5; i++) {
    if (i >= 2) {
        break;
    }
    System.out.println("Yuhu");
}
System.out.println(i);
// Output:
// Yuhu
// Yuhu
// 2

continue will stop the current iteration and will move to the next one. Notice that inside a for loop, it will still run the third section.

int i;
for (i = 0; i < 5; i++) {
    if (i >= 3) {
        break;
    }
    System.out.println("Yuhu");
    if (i >= 1) {
        continue;
    }
    System.out.println("Tata");
}
System.out.println(i);
// Output
// Yuhu
// Tata
// Yuhu
// Yuhu
// 3

Leave a Reply

Your email address will not be published. Required fields are marked *