Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any
intermediate code is bypassed. Here is an example program that uses continue to cause two numbers to be printed on each line:
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program:
0 1
2 3
4 5
6 7
8 9