Two statements, break and continue , can be used in loop statements to provide the loop with additional control.
break immediately ends the innermost loop that contains it. It is generally used with an if statement.
continue only ends the current iteration. Program control goes to the end of the loop body. This keyword is generally used with an if statement.
You have already used the keyword break in a switch statement. You can also use break and continue in a loop. Listings 4.9 and 4.10 present two programs to demonstrate the effect of the break and continue keywords in a loop.
The program in Listing 4.9 adds the integers from 1 to 20 in this order to sum until sum is greater than or equal to 100 . Without the if statement (line 10), the program calculates the sum of the numbers from 1 to 20 . But with the if statement, the loop terminates when the sum becomes greater than or equal to 100 . The output of the program is shown in Figure 4.11(a).
If you changed the if statement as shown below, the output would resemble that in Figure 4.11(b).
if (sum == 100 ) break ;
In this case, the if condition will never be true. Therefore, the break statement will never be executed.
1 public class TestBreak { 2 /** Main method */ 3 public static void main(String[] args) { 4 int sum = ; 5 int number = ; 6 7 while (number < 20 ) { 8 number++; 9 sum += number; 10 if (sum >= 100 ) break ; 11 } 12 13 System.out.println( "The number is " + number); 14 System.out.println( "The sum is " + sum); 15 } 16 } |
The program in Listing 4.10 adds all the integers from 1 to 20 except 10 and 11 to sum . With the if statement in the program (line 9), the continue statement is executed when number becomes 10 or 11 . The continue statement ends the current iteration so that the rest of the statement in the loop body is not executed; therefore, number is not added to sum when it is 10 or 11 . The output of the program is shown in Figure 4.12(a).
Without the if statement in the program, the output would look like Figure 4.12(b). In this case, all of the numbers are added to sum , even when number is 10 or 11 . Therefore, the result is 210 , which is 21 more than it was with the if statement.
1 public class TestContinue { 2 /** Main method */ 3 public static void main(String[] args) { 4 int sum = ; 5 int number = ; 6 7 while (number < 20 ) { 8 number++; 9 if (number == 10 number == 11 ) continue ; 10 sum += number; 11 } 12 13 System.out.println( "The sum is " + sum); 14 } 15 } |
Note
The continue statement is always inside a loop. In the while and do-while loops , the loop-continuation-condition is evaluated immediately after the continue statement. In the for loop, the action-after-each-iteration is performed, then the loop-continuation-condition is evaluated immediately after the continue statement. |
Tip
You can always write a program without using break or continue in a loop. See Review Question 4.13. In general, it is appropriate to use break and continue if their use simplifies coding and makes programs easier to read. |
4.9.1. (Optional) Statement Labels and Breaking with Labels |
Every statement in Java can have an optional label as an identifier. Labels are often associated with loops. You can use a break statement with a label to break out of the labeled loop, and a continue statement with a label to break out of the current iteration of the labeled loop.
The break statement given below, for example, breaks out of the outer loop if ( i * j > 50 ) and transfers control to the statement immediately following the outer loop.
outer: for ( int i = 1 ; i < 10 ; i++) { inner: for ( int j = 1 ; j < 10 ; j++) { if (i * j > 50 ) break outer; System.out.println(i * j); } }
If you replace breakouter with break in the preceding statement, the break statement would break out of the inner loop and continue to stay inside the outer loop.
The following continue statement breaks out of the inner loop if ( i * j > 50 ) and starts a new iteration of the outer loop if i < 10 is true after i is incremented by 1 .
outer: for ( int i = 1 ; i < 10 ; i++) { inner: for ( int j = 1 ; j < 10 ; j++) { if (i * j > 50 ) continue outer System.out.println(i * j); } }
If you replace continue outer with continue in the preceding statement, the continue statement would break out of the current iteration of the inner loop and continue the next iteration of the inner loop if j < 10 is true after j is incremented by 1 .
Note
Some programming languages have a goto statement, but labeled break statements and labeled continue statements in Java are completely different from goto statements. The goto label statement would indiscriminately transfer the control to any labeled statement in the program and execute it. The break label statement breaks out of the labeled loop, and the continue label statement breaks out of the current iteration in the labeled loop. |
4.9.2. (Optional) Example: Displaying Prime Numbers |
This section presents a program that displays the first fifty prime numbers in five lines, each of which contains ten numbers, as shown in Figure 4.13. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
The problem can be broken into the following tasks :
Determine whether a given number is prime.
For number = 2 , 3 , 4 , 5 , 6 , . . ., test whether it is prime.
Count the prime numbers.
Print each prime number, and print ten numbers per line.
Obviously, you need to write a loop and repeatedly test whether a new number is prime. If the number is prime, increase the count by 1. The count is initially. When it reaches 50 , the loop terminates.
Here is the algorithm for the problem:
Set the number of prime numbers to be printed as a constant NUMBER_OF_PRIMES; Use count to track the number of prime numbers and set an initial count to ; Set an initial number to 2 ; while (count < NUMBER_OF_PRIMES) { Test if number is prime; if number is prime { Print the prime number and increase the count; } Increment number by 1 ; }
To test whether a number is prime, check whether it is divisible by 2 , 3 , 4 , up to number/2 . If a divisor is found, the number is not a prime. The algorithm can be described as follows :
Use a boolean variable isPrime to denote whether the number is prime; Set isPrime to true initially; for ( int divisor = 2 ; divisor <= number / 2 ; divisor++) { if (number % divisor == ) { Set isPrime to false Exit the loop; } }
The complete program is given in Listing 4.11.
1 public class PrimeNumber { 2 /** Main method */ 3 public static void main(String[] args) { 4 final int NUMBER_OF_PRIMES = 50 ; // Number of primes to display 5 final int NUMBER_OF_PRIMES_PER_LINE = 10 ; // Display 10 per line 6 int count = ; // Count the number of prime numbers 7 int number = 2 ; // A number to be tested for primeness 8 9 System.out.println( "The first 50 prime numbers are \n" ); 10 11 // Repeatedly find prime numbers 12 while (count < NUMBER_OF_PRIMES) { 13 // Assume the number is prime 14 boolean isPrime = true ; // Is the current number prime? 15 16 // Test if number is prime 17 for ( int divisor = 2 ; divisor <= number / 2 divisor++) { 18 if (number % divisor == ) // the number is not prime 19 isPrime = false ; // Set isPrime to false 20 break ; // Exit the for loop 21 } 22 } 23 24 // Print the prime number and increase the count 25 if (isPrime) { 26 count++; // Increase the count 27 28 if (count % NUMBER_OF_PRIMES_PER_LINE == ) { 29 // Print the number and advance to the new line 30 System.out.println(number); 31 } 32 else 33 System.out.print(number + " " ); 34 } 35 36 // Check if the next number is prime 37 number++; 38 } 39 } 40 } |
This is a complex example for novice programmers. The key to developing a programmatic solution to this problem, and to many other problems, is to break it into subproblems and develop solutions for each of them in turn . Do not attempt to develop a complete solution in the first trial. Instead, begin by writing the code to determine whether a given number is prime, then expand the program to test whether other numbers are prime in a loop.
To determine whether a number is prime, check whether it is divisible by a number between 2 and number/2 inclusive. If so, it is not a prime number; otherwise , it is a prime number. For a prime number, display it. If the count is divisible by 10, advance to a new line. The program ends when the count reaches 50.
Note
The program uses the break statement in line 23 to exit the for loop as soon as the number is found to be a nonprime. You can rewrite the loop (lines 17 “22) without using the break statement, as follows: for ( int divisor = 2 ; divisor <= number / 2 && isPrime; divisor++) { // If true, the number is not prime if (number % divisor == ) { // Set isPrime to false, if the number is not prime isPrime = false ; } } However, using the break statement makes the program simpler and easier to read in this case. |