생산자

Yoo Moon Il

토픽 125 / 봤어요 51

28_[자바] break, continue

2018-07-02 20:48:39

break and continue

You can also control the flow of the loop inside the body of any of the iteration statements by using break and continue. break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration.

This program shows examples of break and continue within for and while loops:

In the for loop, the value of i never gets to 100 because the break statement breaks out of the loop when i is 74. Normally, you’d use a break like this only if you didn’t know when the terminating condition was going to occur. The continue statement causes execution to go back to the top of the iteration loop (thus incrementing i) whenever i is not evenly divisible by 9. When it is, the value is printed.

The second for loop shows the use of foreach, and that it produces the same results.

Finally, you see an “infinite” while loop that would, in theory, continue forever. However, inside the loop there is a break statement that will break out of the loop. In addition, you’ll see that the continue statement moves control back to the top of the loop without completing anything after that continue statement. (Thus printing happens in the second loop only when the value of i is divisible by 10.) In the output, the value 0 is printed, because 0 % 9 produces 0.

A second form of the infinite loop is for(;;). The compiler treats both while(true) and for(;;) in the same way, so whichever one you use is a matter of programming taste.