Java Reference
In-Depth Information
5.9 Keywords break and continue
The break and continue keywords provide additional controls in a loop.
Key
Point
Pedagogical Note
Two keywords, break and continue , can be used in loop statements to provide addi-
tional controls. Using break and continue can simplify programming in some cases.
Overusing or improperly using them, however, can make programs difficult to read and
debug. ( Note to instructors : You may skip this section without affecting students' under-
standing of the rest of the topic.)
You have used the keyword break in a switch statement. You can also use break in a loop
to immediately terminate the loop. ListingĀ 5.12 presents a program to demonstrate the effect
of using break in a loop.
break statement
L ISTING 5.12
TestBreak.java
1 public class TestBreak {
2
public static void main(String[] args) {
3
int sum = 0 ;
4
int number = 0 ;
5
6 while (number < 20 ) {
7 number++;
8 sum += number;
9 if (sum >= 100 )
10
break ;
break
11 }
12
13 System.out.println( "The number is " + number);
14 System.out.println( "The sum is " + sum);
15 }
16 }
The number is 14
The sum is 105
The program in ListingĀ 5.12 adds integers from 1 to 20 in this order to sum until sum is
greater than or equal to 100 . Without the if statement (line 9), the program calculates the
sum of the numbers from 1 to 20 . But with the if statement, the loop terminates when sum
becomes greater than or equal to 100 . Without the if statement, the output would be:
The number is 20
The sum is 210
You can also use the continue keyword in a loop. When it is encountered, it ends the cur-
rent iteration and program control goes to the end of the loop body. In other words, continue
breaks out of an iteration while the break keyword breaks out of a loop. ListingĀ 5.13 presents
a program to demonstrate the effect of using continue in a loop.
continue statement
L ISTING 5.13
TestContinue.java
1 public class TestContinue {
2
public static void main(String[] args) {
3
int sum = 0 ;
 
 
 
Search WWH ::




Custom Search