Java Reference
In-Depth Information
Use break to Exit a Loop
It is possible to force an immediate exit from a loop, bypassing any remaining code in the
body of the loop and the loop's conditional test, by using the break statement. When a
break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop. Here is a simple example:
This program generates the following output:
As you can see, although the for loop is designed to run from 0 to num (which in this case
is 100), the break statement causes it to terminate early, when i squared is greater than or
equal to num .
The break statement can be used with any of Java's loops, including intentionally infin-
ite loops. For example, the following program simply reads input until the user types the
letter q:
Search WWH ::




Custom Search