Skip to main content

Continue Statement in Java

  • The continue statement is used to skip the current iteration of a loop and continue with the next iteration.

  • It works in for, while, and do-while loops. When a continue statement is encountered, the loop's remaining code is skipped for the current iteration, and the next iteration begins.

  • It is a control structure in Java that allows you to skip the current iteration of a loop and proceed to the next iteration.

  • The continue statement is useful when you want to skip over certain conditions within a loop without terminating the loop entirely.

Syntax of the continue Statement

Here is the basic syntax of the continue statement:

continue;

The continue statement can be used within:

  • for loops

  • while loops

  • do-while loops

Using continue in Loops

Example: Using continue in a for Loop

Let's look at an example of using continue in a for loop. Consider the following code:

public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("Odd number: " + i);
}
}
}

Explanation:

  • Initialization: int i = 0; initializes the counter variable i to 0.

  • Condition: i < 10 is the loop condition.

  • Loop Body: The code inside the loop checks if i is even using if (i % 2 == 0).

  • Continue Statement: If i is even, the continue statement is executed, skipping the rest of the loop body and proceeding to the next iteration.

  • Print Statement: If i is odd, System.out.println("Odd number: " + i); prints the current value of i.

The output will be:

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

Note: We can use continue statement in while and do while loops too. Using continue statement in while and do while loop is similar to using continue statement in for loop.

Summary

  • continue statement: Used to skip the current iteration of a loop and proceed to the next iteration.

  • Syntax: continue;

  • Loops: Can be used in for, while, and do-while loops to skip over certain conditions.

  • Common Pitfalls: Be mindful of unintended infinite loops, skipping necessary code, and using continue outside of loops.

The continue statement is a useful tool for controlling the flow of your loops in Java.