Command Palette

Search for a command to run...

Back to the lesson: Topic 2.8 — break, continue and Labels
Core Java · Example 1 of 4

break and continue

break leaves the innermost loop or switch at once; continue skips the rest of the current iteration and moves to the next. A label lets either one target an outer loop, which is the clean way to stop nested loops.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the numbers from 1 to 20, skipping multiples of 4, and stop completely when you reach a number greater than 15.

02

Find the first pair of numbers in {3, 8, 11, 4, 7} that add up to 15, using nested loops and a labelled break, and print the pair.

03

Using continue, print only the words in {"apple", "", "kiwi", " ", "plum"} that are not blank.

Explain it without notes

01

What's the difference between break and continue?

02

Why does a break inside a switch inside a loop not stop the loop, and how do you stop the loop?

03

How does continue behave differently in a for loop and a while loop?

04

What alternatives to a labelled break exist for leaving nested loops?

break and continue
Sign in to run this example in your browser.

Expected output

First negative at index 2
Multiples of 3: 3 6 9
Sum of non-negatives: 20