break Statement

A break statement lets you exit from a loop created by a while or do statement. When a break statement is executed in a loop, the loop ends immediately. Any remaining statements in the loop are ignored, and the next statement executed is the statement that follows the loop.

Here’s an example that looks like it would count numbers from 1 to 20. However, when it gets to the number 12, it breaks out of the loop:

int number = 1;

while (number <= 20)

{

if (number == 12)

break;

System.out.print(number + “ “);

number++;

}

When you run this code, the following line displays on the console:

1 2 3 4 5 6 7 8 9 10 11

CrossRef.eps The break statement can also be used in a switch statement. For more information, see switch Statement.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.