Java Reference
In-Depth Information
Block1:
{
Block2:
{
...
OuterLoop:
for(...)
{
break Block1;
while(...)
{
breaks out beyond
Block1
...
break Block2;
...
break OuterLoop;
breaks out beyond
Block2
}
...
breaks out beyond
OuterLoop
}
...
} // end of Block2
...
} // end of Block1
...
The labeled break enables you to break out to the statement following an enclosing block or loop that
has a label regardless of how many levels there are. You might have several loops nested one within the
other, and using the labeled break you could exit from the innermost loop (or indeed any of them) to
the statement following the outermost loop. You just need to add a label to the beginning of the relevant
block or loop that you want to break out of, and use that label in the break statement.
Just to see it working we can alter the previous example to use a labeled break statement:
public class FindPrimes {
public static void main(String[] args) {
int nPrimes = 50; // The maximum number of primes required
// Check all values from 2 to nValues
OuterLoop:
for(int i = 2; ; i++) { // This loop runs forever
// Try dividing by all integers from 2 to i-1
for(int j = 2; j < i; j++) {
if(i % j == 0) { // This is true if j divides exactly
continue OuterLoop; // so exit the loop
}
}
// We only get here if we have a prime
System.out.println(i); // so output the value
if(--nPrimes == 0) { // Decrement the prime count
break OuterLoop; // It is zero so we have them all
}
}
// break OuterLoop goes to here
}
}
Search WWH ::




Custom Search