Continue Statement in Java
The continue statement in Java is used to skip the current iteration of a loop and proceed to the next iteration. It allows you to control the flow of the program by bypassing specific parts of the loop based on certain conditions.
Key Points on Continue Statement:
- Can be used in for, while, and do-while loops.
- Only affects the innermost loop in which it is used.
- Useful for skipping specific iterations when certain conditions are met.
- Can improve readability by avoiding deeply nested conditional statements.
Syntax of Continue Statement:
Syntax Example
continue; // Skips the current iteration of the loop
Example of Continue Statement in a Loop:
This example demonstrates the use of the continue statement within a loop to skip specific numbers.
Code Example 1
public class ContinueInLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the even numbers
}
System.out.println(i);
}
}
}
Output for Code Example 1:
1
3
5
7
9
3
5
7
9
Example of Continue Statement in a While Loop:
This example shows how to use the continue statement in a while loop.
Code Example 2
public class WhileContinue {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
i++;
if (i % 3 == 0) {
continue; // Skip the numbers that are multiples of 3
}
System.out.println(i);
}
}
}
Output for Code Example 2:
1
2
4
5
7
8
10
2
4
5
7
8
10
Using Continue in Nested Loops:
This example illustrates how the continue statement affects nested loops.
Code Example 3
public class NestedLoopContinue {
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 the inner loop when j equals 2
}
System.out.print("i: " + i + ", j: " + j + " | ");
}
System.out.println(); // New line after inner loop
}
}
}
Output for Code Example 3:
i: 1, j: 1 |
i: 1, j: 3 |
i: 2, j: 1 |
i: 2, j: 3 |
i: 3, j: 1 |
i: 3, j: 3 |
i: 1, j: 3 |
i: 2, j: 1 |
i: 2, j: 3 |
i: 3, j: 1 |
i: 3, j: 3 |
Detailed Explanation:
- Usage in Loops: When the continue statement is encountered, the current iteration is skipped, and control moves to the next iteration of the loop.
- Nested Loops: The continue statement only affects the innermost loop in which it is placed.
- Improves Readability: Helps to avoid complicated nested conditions by allowing a clean exit from the current iteration.
The continue statement is a useful tool for controlling the flow of loops in Java, enabling developers to skip unnecessary iterations and make code cleaner and more efficient.