Continue Statement in Java
The continue statement in Java is a control flow statement used to skip the current iteration of a loop and move the execution to the next iteration.
The continue keyword is mainly used with for loop, while loop, and do while loop when we want to ignore a specific condition but continue the remaining loop execution.
What is Continue Statement in Java?
A continue statement in Java is a jump statement that changes the normal flow of a loop. When the continue statement executes, the remaining code inside the current loop iteration is skipped.
After skipping the current iteration, the control moves to the next iteration of the loop.
Syntax of Continue Statement in Java
continue;
How Continue Statement Works in Java?
- The loop starts execution normally.
- When the continue statement is reached, the current iteration stops.
- The remaining statements inside the loop are skipped.
- The next iteration starts automatically.
Continue Statement Example in Java
public class Main {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue;
}
System.out.println(i);
}
}
}
2
4
5
Explanation of Example
In the above example, when the value of i becomes 3,
the continue statement executes. The print statement is skipped for that
iteration, and the loop continues with the next value.
Continue Statement with While Loop
int i = 1;
while(i <= 5) {
i++;
if(i == 3) {
continue;
}
System.out.println(i);
}
Continue Statement in Nested Loop
In nested loops, the continue statement affects the loop in which it is written. It skips the current iteration of that particular loop.
for(int i = 1; i <= 3; i++) {
if(i == 2) {
continue;
}
System.out.println(i);
}
Types of Continue Statement in Java
Simple Continue
Skips the current iteration of the nearest loop.
Labeled Continue
Used to skip an iteration of a specific outer loop.
Advantages of Continue Statement
Loop Control
Provides better control over loop execution.
Skip Values
Helps ignore unwanted values during iteration.
Cleaner Code
Reduces complex conditional logic inside loops.
Difference Between Break and Continue Statement
- Break: Terminates the complete loop immediately.
- Continue: Skips only the current iteration and continues the loop.
When to Use Continue Statement?
- When you want to skip specific values in a loop.
- When some conditions should be ignored during execution.
- When processing only required elements from a collection.