0
0
JavaHow-ToBeginner · 3 min read

How to Use Continue in Java: Syntax and Examples

In Java, the continue statement skips the current iteration of a loop and moves to the next one. It can be used inside for, while, and do-while loops to control flow efficiently.
📐

Syntax

The continue statement is used inside loops to skip the rest of the current iteration and jump to the next iteration.

  • continue; - Skips to the next iteration of the nearest enclosing loop.
  • continue label; - Skips to the next iteration of the loop identified by the label.
java
for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // skip when i is 2
    }
    System.out.println(i);
}
Output
0 1 3 4
💻

Example

This example shows how continue skips printing the number 3 inside a for loop.

java
public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // skip printing 3
            }
            System.out.println("Number: " + i);
        }
    }
}
Output
Number: 1 Number: 2 Number: 4 Number: 5
⚠️

Common Pitfalls

One common mistake is using continue outside loops, which causes a compile error. Another is forgetting that continue only skips the current iteration, not the entire loop.

Also, using continue in nested loops without labels can lead to confusion about which loop it affects.

java
public class PitfallExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    continue; // skips inner loop iteration when j is 2
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}
Output
i=1, j=1 i=1, j=3 i=2, j=1 i=2, j=3 i=3, j=1 i=3, j=3
📊

Quick Reference

  • continue; - skips to next iteration of the nearest loop.
  • continue label; - skips to next iteration of the labeled loop.
  • Use inside for, while, or do-while loops only.
  • Cannot be used outside loops.

Key Takeaways

Use continue to skip the current loop iteration and proceed to the next one.
continue works inside all loop types: for, while, and do-while.
Avoid using continue outside loops to prevent compile errors.
In nested loops, use labeled continue to specify which loop to continue.
Remember that continue skips only the current iteration, not the entire loop.