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