Continue Statement

Continue statement is used when we want to skip the rest of the statement in the body of the loop and continue with the next iteration of the loop.
There are two forms of continue statement in Java.

1. Unlabeled Continue Statement
2. Labeled Continue Statement

Unlabeled Continue Statement

This form of statement causes skips the current iteration of innermost for, while or do while loop.

For example,

for(int var1 =0; var1 < 5 ; var1++)
{

for(int var2=0 ; var2 < 5 ; var2++)
{
if(var2 == 2)
continue;

System.out.println("var1:" + var1 + ", var2:"+ var2);

}

}

In above example, when var2 becomes 2, the rest of the inner for loop body will be skipped.

Labeled Continue Statement

Labeled continue statement skips the current iteration of the loop marked with the specified label. This form is used with nested loops.

For example,

Outer:
for(int var1 =0; var1 < 5 ; var1++)
{

for(int var2=0 ; var2 < 5 ; var2++)
{
if(var2 == 2)
continue Outer;

System.out.println("var1:" + var1 + ", var2:"+ var2);

}

}

In the above example, when var2 becomes 2, rest of the statements in body of inner as well outer for loop will be skipped, and next iteration of the Outer loop will be executed.

Continue Statement

Add Comment

    • not similar to if/else..
      Suppose i have an example to print 1-50, but at every 3rd place i have to print “sanjeev” and at every 5th place have to print “Singh”.
      Like 1 , 2, sanjeev, 4 , singh…..so on…

  • i have an example to print 1-50, but at every 3rd place i have to print “sanjeev” and at every 5th place have to print “Singh”.
    Like 1 , 2, sanjeev, 4 , singh…..so on…

    public class Test21 {
    public static void main(String[] args) {
    for(int i=1; i<=50; i++){
    if (i%15==0 ) {
    System.out.println(“sanjeev ranjan”);
    continue;
    }
    if (i%5==0 ) {
    System.out.println(“sanjeev”);
    continue;
    }
    if (i%3==0 ) {
    System.out.println(“ranjan”);
    continue;
    }
    System.out.println(i);
    }

    }

    }

Sponsors

Facebook Fans