Java continue Statement

On certain occasions, it is useful to force an early iteration of the loop i.e., you might want to continue running the loop but stop processing the remainder of code in its body for this particular iteration. This is, in effect, a goto just pass the body of the loop to the end of the loop. The continue statement performs such an action.

In while and do-while loops, the continue statement causes a control to be transferred directly to the conditional expression that controls the loop. In the for loop, the control goes first to the iteration portion of the for statement and then to the conditional expression. And for all three loops (for, while, and do-while), any intermediate code is bypassed.

Java continue Statement Example

Here is an example program that uses the continue statement to cause the two numbers to be printed on each line :

/* Java Program Example - Java continue Statement
 * This program demonstrates the continue keyword
 */

public class JavaProgram
{   
    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();
        }
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java continue statement

As with the break statement, continue may define a label to report which enclosing loop to continue. Here is an example program that uses the continue keyword to print the triangular multiplication table for 0 though 9 :

/* Java Program Example - Java continue Statement
 * Using continue with a label 
 */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        outer: for(int i=0; i<10; i++) {
            for(int j=0; j<10; j++) {
                if(j > i) {
                    System.out.println();
                    continue outer;
                }
                System.out.print("  " + (i * j));
            }
        }
        System.out.println();
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java continue keyword

The continue statement in above example terminates the loop counting j and then continues with the next iteration of the loop counting i.

Java Online Test


« Previous Tutorial Next Tutorial »