Curriculum
In Java, the continue
statement is used in loops to skip to the next iteration of the loop without executing the remaining code in the loop for the current iteration. When a continue
statement is encountered, the loop skips any remaining statements in the current iteration and immediately begins the next iteration.
Here’s an example that uses a continue
statement in a for loop:
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } System.out.println(i); }
In this example, the for loop iterates over the numbers 1 through 10. However, when the loop encounters an even number, the continue
statement is executed, causing the loop to skip the remaining statements in the current iteration and move on to the next iteration. Therefore, only the odd numbers (1, 3, 5, 7, 9) will be printed to the console.
The continue
statement is often used to skip over certain iterations of a loop that meet a specific condition, as in the previous example. It can also be used in nested loops to skip to the next iteration of the inner loop without affecting the outer loop.
Here’s an example that uses a continue
statement in a nested for loop:
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { if (j == 3) { continue; } System.out.print(j + " "); } System.out.println(); }
In this example, the outer for loop iterates over the numbers 1 through 5, and the inner for loop iterates over the numbers 1 through 5 for each iteration of the outer loop. However, when the inner loop encounters the number 3, the continue
statement is executed, causing the inner loop to skip the remaining statements in the current iteration and move on to the next iteration. Therefore, for each iteration of the outer loop, the numbers 1, 2, 4, and 5 will be printed to the console.
Overall, the continue
statement is a useful tool for controlling the flow of a loop and skipping over certain iterations based on specific conditions.