Java – Continue Statement

In Java, the continue statement allows the application to skip a block of code for the current loop iteration. The continue statement returns the programme to the beginning of the loop whenever the condition is met.

When the continue statement is used in a nested loop (loop inside the loop), it skips the code block of the innermost loop as soon as the condition is met.

Continue statement with While loop

If the value of variable j becomes 4, the continue statement is used to bypass the while loop in the example below.

public class MyClass {
  public static void main(String[] args) {
    int j = 0;
    while (j < 6){
      j++;
      if(j == 4){
        System.out.println("this iteration is skipped.");
        continue;
      }
      System.out.println(j); 
    }
  }
}

The following is the result of the aforementioned code:

1
2
3
this iteration is skipped.
5
6

Continue statement with For loop

If the value of variable i becomes 4, the continue statement is used to skip the for loop in the example below.

public class MyClass {
  public static void main(String[] args) {
    for (int i = 1; i <= 6; i++){
      if(i == 4){
        System.out.println("this iteration is skipped.");
        continue;
      }
      System.out.println(i); 
    }
  }
}

The output of the above code will be:

1
2
3
this iteration is skipped.
5
6

Continue statement with Nested loop

When the condition is met, the Continue statement skips the inner loop’s code block. Only when j = 100 does the software bypass the inner loop in the example below.

//Nested loop without continue statement
public class MyClass {
  public static void main(String[] args) {
    System.out.println("# Nested loop without continue statement");
    for (int i = 1; i <= 3; i++){
      for (int j = 10; j <= 1000; j = j * 10){
        System.out.println(i*j);
      }
    }
  }
}

The output of the above code will be:

# Nested loop without continue statement
10
100
1000
20
200
2000
30
300
3000
//Nested loop with continue statement
public class MyClass {
  public static void main(String[] args) {
    System.out.println("# Nested loop with continue statement");
    for (int i = 1; i <= 3; i++){
      for (int j = 10; j <= 1000; j = j * 10){
        if(j == 100 ){
          continue;
        }
        System.out.println(i*j);
      }
    }
  }
}

The output of the above code will be:

# Nested loop with continue statement
10
1000
20
2000
30
3000

Click here to open the online compiler.

Next: ​Java – Break Statement

Leave a Reply

Your email address will not be published. Required fields are marked *