Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 12 Apr 2016
continue stops a particular iteration in a loop. e.g., If a loop has 15 iterations and having 5 lines of code, if in iteration 10 the continue statement is encountered at line 3, then the lines below that i.e. line 4 and 5 will not be executed, but it continues with iteration 6,7 etc.

Print even numbers
class PrintEvenNumbers
{
    public static void main(String arg[])
    {
        for(int i = 1; i < 5; i++)
        {
            System.out.println("processing " + i); // LINE A
        
            boolean odd = (i % 2 == 1);
        
            if( odd ) continue; // LINE B
        
            System.out.println(i + " is even"); // LINE C
        }    
    }
}
OUTPUT

processing 1
processing 2
2 is even
processing 3
processing 4
4 is even

DESCRIPTION

Here i is iterated from 1 to 5, when i = 1, it first prints processing 1 and then variable odd is evaluated which will be true. So continue will be called at LINE B. This will cause the control to go back to the first statement which is LINE A. LINE C will not be executed.
Next when i becomes 2, it prints processing 2 and odd will become false, so continue will not be called. So LINE C executes, printing 2 is even. These iterations continue until i becomes 5 and prints the rest of output.

THINGS TO TRY
  • In the above program try to print odd numbers instead of even numbers.
  • Try for the below code.
    int i = 0;
    while (i < 5)
    {
        System.out.println("value of i: " + i);
        i++;
        if (true)
            continue; // LINE A    
        System.out.println("value after continue: " + i); // LINE B
    }
    The output for the above code is :
    value of i: 0
    value of i: 1
    value of i: 2
    value of i: 3
    value of i: 4

    We can see LINE B is not executed because of continue at LINE A.
  • Remove if condition at LINE A in the above sample code to see a compilation error since continue should be in a if block if it is not the last sentence.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App