Hi everyone, welcome back. In this article, we will be going over the continue statement in Java and see how it works. The continue statement is used to stop a current iteration of a loop and continue onto the next iteration. This can be done within a for loop or a while loop and we will go over an example of both. With this introduction out of the way, let’s get into it.
Example: Continue Statement in a For Loop
Let’s see an example of us using the continue statement in a for loop:
for(int i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}Output:
0
1
2
4
As we can see in the example above, we are executing our continue statement when our “i” variable is equal to 3. Looking at the output, we can see that we successfully completed the iteration of all the other values besides 3. This verifies that we have successfully stopped the iteration where “i” was equal to 3 and continued onto the next iteration.
Example: Continue Statement in a While Loop
Now, let’s see an example of us using the continue statement in a while loop:
int i = 0;
while(i < 5) {
i++;
if (i == 3) {…