Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Continue Statement



The continue statement complements the break statement. Its use is restricted to while and for loops. When a continue statement is executed, control is immediately passed to the test condition of the nearest enclosing loop to determine whether the loop should continue. All subsequent statements in the body of the loop are ignored for that particular loop iteration.

The following diagram shows the diagrammatic explanation of the continue statement −

Continue Statement

Example - Usage of continue Statement in for loop

Following is an example of the continue statement in a for loop−

Example.groovy

class Example {
   static void main(String[] args) {
      int[] array = [0,1,2,3];
		
      for(int i in array) {
         if(i == 2)
         continue;
         println(i);
      }
   }
}

Output

The output of the above code would be −

0 
1 
3

Example - Skipping Specific Values in a Loop

Following is an example of the continue statement to bypass certain iterations based on conditions.

Example.groovy

class Example {
   static void main(String[] args) {
      for (int i = 1; i <= 10; i++) {
         if (i % 2 == 0) {
            continue; // Skip even numbers
         }
         println(i);
      }
   }
}

Output

The output of the above code would be −

1
3
5
7
9

Example - Skipping Iteration in Nested Loops

The continue statement can be used to skip specific conditions inside nested loops without exiting them.

In this example, we are skipping a specific condition in a grid output −

Example.groovy

class Example {
   static void main(String[] args) {
      for (int i = 1; i <= 3; i++) {
         for (int j = 1; j <= 3; j++) {
            if (i == j) {
               continue; // Skip when row index equals column index
            }
            System.out.println("i: " + i + ", j: " + j);
         }
      }
   }
}

Output

The output of the above code would be −

i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
Advertisements