CodeBlanks Logo Icon CodeBlanks

break and continue

Learn to exit with break and skip with continue.

break and continue

break exits the loop entirely; continue skips the current turn and moves to the next.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // loop ends
    }
    System.out.println(i);
}

This prints 0, 1, 2, 3, 4; when i == 5 the loop exits. break and continue are usually used inside an if; without a condition, the rest of the loop never runs.

A continue example

continue skips the rest of the current turn and moves to the next. To skip even numbers:

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

This prints only odd numbers: 1, 3, 5. When continue is called, the code below it is skipped for that turn, but the loop continues with the next i.

Practice Stop at 5

Write a Main class with a main method. Write for (int i = 0; i < 10; i++). When if (i == 5) use break; to exit. Print System.out.println(i) each turn.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break;
            }
            System.out.println(i);
        }
    }
}

Expected output

0
1
2
3
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the break/continue concepts

Term Meaning
break Exit loop
continue Skip turn
if Condition
{ } Block

2 What does break do?

  • Starts the loop
  • Exits the loop Correct answer
  • Skips a turn
  • Nothing

Explanation: break exits the loop entirely.

3 Complete the break call

Question
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        ____;
    }
    System.out.println(i);
}
Answer
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}

Explanation: break exits the loop when i == 5.

All lessons in Beginner