CODE
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
}
}
}
processing 1
processing 2
2 is even
processing 3
processing 4
4 is even
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.
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
}
LINE B
is not executed because of continue
at LINE A
.
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.