Monday, January 13, 2020

continue statement

The continue statement

The continue statement is used inside a loop when there is a requirement to jump to the next iteration of the loop immediately. The continue statements can be used only within some loop(for-loop, while and do-while, etc) and transfers control to the end of the loop's body. In the case of a while and do-while loops, this causes the loop expression to be evaluated next. In the for-loop, this causes the increment/decrement(update) to be evaluated before the loop expression.

continue statement java
continue statement

The example continue-statement


public class Demo {
     public static void main(String[] args) {
            int arr[][]= {{0,1,0,0},
                      {0,0,0,0},
                      {0,1,1,0},
                      {0,0,0,1}};
                  for(int i=0;i<4;i++)
                  {
                   for(int j=0;j<4;j++)
                   {
                    if(arr[i][j]==1)
                    {
                     continue;//statements after continue will not be
                    }     //executed if condition is fulfilled
                    System.out.print(arr[i][j]+"\t");
                   }
                   System.out.println();
                  }
            }
}


Output:

0 0 0
0 0 0 0
0 0
0 0 0

The labeled continue statements

We can also use labeled continue, labels are used to uniquely identify the loops if they are nested inside each other. like

continue label_name;

The continue statements are generally used inside if statement,

labeled continue statements
labeled continue statements

The example labeled continue-statement


public class Demo {
     public static void main(String[] args) {
           label_outer:
                 for (int i = 1; i < 6; ++i) {
                    for (int j = 1; j < 5; ++j) {
                       if (i == 3 || j == 2)
                          continue label_outer;
                       System.out.println("i = " + i + "; j = " + j);
                    }
                 }
            }
}


Output:

i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1

Video Tutorial