Java Reference
In-Depth Information
In general, you can use the labeled
continue
to exit from an inner loop to any enclosing outer loop, not
just the one immediately enclosing the loop containing the labeled
continue
statement.
Using the break Statement in a Loop
You have seen how to use the
break
statement in a
switch
block. Its effect is to exit the
switch
block and
continue execution with the first statement after the
switch
. You can also use the
break
statement to break
out from a loop. When
break
is executed within a loop, the loop ends immediately, and execution continues
with the first statement following the loop. To demonstrate this, you write a program to find prime numbers.
In case you have forgotten, a prime number is an integer that is only exactly divisible by itself and 1.
TRY IT OUT: Calculating Primes I
There's a little more code to this than the previous example. This program finds all the primes from 2 to
50:
public class Primes {
public static void main(String[] args) {
int nValues = 50;
// The maximum value to be
checked
boolean isPrime = true;
// Is true if we find a prime
// Check all values from 2 to nValues
for(int i = 2; i <= nValues; ++i) {
isPrime=true;
// Assume the current i is
prime
// 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
isPrime = false;
// If we got here, it was an
exact division
break;
// so exit the loop
}
}
// We can get here through the break, or through completing the
loop
if(isPrime)
// So is it prime?
System.out.println(i);
// Yes, so output the value
}
}
}