Font Awesome Icons

Tutorial

Java Continue

The continue statement in Java skips the current iteration of a loop (for, while, do…while, etc) and the control of the program moves to the end of the loop. And, the test expression of a loop is evaluated.Whenever it is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration.

Syntax:

continue;

continue statement inside for loop

class C1 {
public static void main(String args[]){
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.print(j+” “);
}
}
}

continue statement inside while loop

class C2 {
public static void main(String args[]){
int counter=8;
while (counter >=0)
{
if (counter==7)
{
counter–;
continue;
}
System.out.print(counter+” “);
counter–;
}
}

}

continue statement inside do-while loop

class C3 {
public static void main(String args[]){
int j=0;
do
{
if (j==5)
{
j++;
continue;
}
System.out.print(j+ ” “);
j++;
}
while(j<9);
}
}

labeled continue statement

We can use the labeled continue statement to terminate the outermost loop very easily.

class C4 {
public static void main(String[] args) {
// this is outer loop
first:
for (int i = 1; i < 6; ++i) {
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)
// skips the iteration of label (outer for loop)
continue first;
System.out.println(“i = ” + i + “; j = ” + j);
}
}
}
}

Note:Most often the labeled continue statement is  ignored as it makes the code not very readable and makes the code more complex.