Breaking Iteration Using break-statements

When executing for-statements or while-statement the iteration can be terminated by executing a break-statement somewhere within the loop. A break-statement is executed within an iteration statement such as a for- or while-statement terminates the enclosing iteration immediately without executing the rest of the iteration statement body. In the case of a while-loop, the loop is terminated without executing the while-predicate.


A break-statement has the following syntax, and is only allowed inside a for-loop or a while-loop:


break


For example, the following function findElement searches an Integer array for a specific element. The search is done by a for-loop, which is terminated by a break-statement when the correct index position has been found and assigned to the result variable called position.