← Back to Week 2 Hub

break vs continue

Two ways to control loop flow: stop entirely, or skip and keep going.

Click Step or Play to begin

break
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
break;
}
sum += i;
}
// sum = ?
i
-
sum
0
continue
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue;
}
sum += i;
}
// sum = ?
i
-
sum
0

When to Use Each

break — Stop the loop completely

Common for search: once you find what you need, stop looking. No point checking the rest.

// Find the first even number
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 0) {
        System.out.println("Found: " + i);
        break;
    }
}

continue — Skip this iteration, keep going

Common for filtering: skip items you don't want, process only the ones you do.

// Print only odd numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i);
}

Alternative to continue: Flip the condition

You can always replace continue by inverting the if condition. Many programmers prefer this because it avoids an extra keyword and keeps the logic clearer.

WITH continue
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) {
        continue;
    }
    sum += i;
}
WITHOUT continue (flipped)
for (int i = 1; i <= 10; i++) {
    if (i % 3 != 0) {
        sum += i;
    }
}

Predict the Output

Challenge 1: What does this print?

int count = 0;
for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    count++;
}
System.out.println(count);

Challenge 2: What does this print?

int total = 0;
for (int i = 1; i <= 6; i++) {
    if (i % 2 == 0) {
        continue;
    }
    total += i;
}
System.out.println(total);

Challenge 3: What does this print?

int result = 0;
for (int i = 10; i >= 1; i--) {
    if (i < 5) {
        break;
    }
    if (i > 8) {
        continue;
    }
    result += i;
}
System.out.println(result);
Tip: Many programmers avoid continue — you can always replace it by flipping the if condition. But break is widely used for early exit from search loops.

Both sides use the same loop — only the keyword changes. Watch how different the results are.

← Loop Types: while vs do/while vs for Arrays: Memory & Indexing →