Introduction to Break and Continue
Inside the body of any of the iteration statements you can also control the flow of the loop by using break and continue statements. The break statement quits the loop executing the rest of the statements in the loop. The continue statement stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration.
Syntax
for (initialization; boolean-expression; increment) {
if (boolean-expression)
break;
if (boolean-expression)
continue;
statement(s)
}
Example
1. /**
2. * @(#)BreakAndContinueDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/11
7. */
8.
9. public class BreakAndContinueDemo {
10.
11. /**
12. * Creates a new instance of <code>BreakAndContinueDemo</code>.
13. */
14. public BreakAndContinueDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23. for (int i=1; i<11; i++) {
24.
25. if ( i == 5)
26. continue;
27.
28. if ( i == 8 )
29. break;
30.
31. System.out.println("Count is: " + i);
32.
33.
34. }
35. }
36. }
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 6
Count is: 7
