AI Hints
Home›Java Tutorial›break and continue, Nested Loops and Loop Patterns
Java · Lesson 40 of 120

break and continue

Leave or skip.

⏱ 2 min read▶ Video at 51:02🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Sometimes you need to leave a loop early, or skip one lap. Break leaves the loop completely. Continue skips to the next lap.

  • break: leave now
  • continue: skip this lap
  • Inside any loop

break

We look through the numbers one to ten. When I is five, we print a message, and break. Break jumps straight out of the loop, to the line after it. Run it. One to four are checked, then we stop at five.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                System.out.println("Found 5, stopping.");
                break;
            }
            System.out.println("Checking " + i);
        }
        System.out.println("After the loop");
    }
}
Output
Checking 1
Checking 2
Checking 3
Checking 4
Found 5, stopping.
After the loop

continue

Here, when I divides by three exactly, we continue. Continue skips the rest of this lap, and goes on to the next one. Run it. Three, six, and nine are missing.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue;
            }
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
Output
1 2 4 5 7 8 10

break or continue

Break ends the whole loop, for example when you've found what you were looking for. Continue skips just one lap, for example to ignore values you don't want.

break

  • Leaves the loopFound it, stopJumps after the loop

continue

  • Skips one lapIgnore this oneJumps to the next lap

Summary

Break leaves a loop early. Continue skips the rest of the current lap. Next, loops inside loops.

Key takeaways
  • break: leave
  • continue: skip
  • Use with if
Next up: Nested Loops — loops inside loops