In Java, the continue
keyword acts as a control statement, allowing you to interrupt the current iteration of a loop (for or while) and proceed directly to the next iteration. Statements following the continue
keyword within the loop will be skipped. The syntax is as follows:
for/while (expressions) {
// Statements 1...
if (condition) {
continue;
}
// Statements 2...
}
Skipping Even Numbers in a For Loop
for (int i = 1; i < 100; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
In this example, the continue
keyword is used to skip even values of the variable i
, resulting in the printing of all odd numbers from 1 to 100.
Generating a List of Even Numbers with a While Loop
int count = 1;
while (count <= 100) {
if (count % 2 != 0) {
count++;
continue;
}
System.out.println(count);
count++;
}
Here, the while loop produces a list of even numbers from 1 to 100 by using the continue
statement to skip odd values.
By strategically employing the continue
keyword, you can control the flow of your loops to meet specific conditions and streamline your code execution.