Inside the body of the iteration statements you can also control the flow of the loop 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 a new iteration. This program shows examples of break and continue within for and while loops:
public class BreakAndContinue
{
public static void main(String[] args)
{
for(int i=0;i<100;i++)
{
if(i==74) break; // Next iteration
System.out.println(i);
}
int i=0;
// An infinite loop
while(true){
i++;
int j=i*27;
if(j==1269) break; // Out of loop
if(i%10!=0) continue; // Top of loop
System.out.println(i);
}
}
}
In the for loop the value of I never gets to 100 because the break statement breaks out of the loop when it is 74. Normally, you would 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.
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.
