break and continue
Skip and exit iterations.
Why Control a Loop?
Loops repeat code, but sometimes you need to stop early or skip an item.
Java gives you two simple tools for this: break ends the loop completely, and continue skips to the next round.
In this lesson you will learn exactly when each one fires and how they change a loop's flow.
The break Statement
The break keyword stops the nearest loop immediately.
Execution jumps to the first line after the loop. Any remaining iterations are abandoned.
Below, the loop stops as soon as i reaches 3.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println("i = " + i);
}
System.out.println("Done");
}
}All lessons in this course
- break and continue
- Labeled break
- Labeled continue
- Avoiding Spaghetti Flow