Continue Statement in Java

Continue Statement in Java

Now let’s have a look at the continue keyword. Well, the continue keyword is another keyword that is useful at times. As the name of the keyword says it all, here, when we use the continue keyword, it does mean skip. Nothing more complicated. If you want to skip a certain iteration, you can clearly use the continue keyword.

Let’s consider that we want to iterate through all the integers from 1 to 100, and just print all the even numbers. So, we can straightaway write that if we find some odd number, we have to skip that iteration and just move to the next iteration doing nothing. This is pretty much straightforward, right?

Continue Statement in Java

In other words, when we use the continue keyword for some condition, then we are just skipping everything for that particular condition, and moving to the next iteration. Let’s consider an example of printing all the even numbers only while iterating through 0 to 100.

public class Loop {
public static void main(String[] args) {
for (int i = 0;i<=100;i++){
if (i%2 !=0){ // this is like… if remainder is not zero, continue to next iteration
continue;
}
System.out.println(“Even number: ” + i);
}
System.out.println(“End of the for loop.”);
}
}

So, here, we kind of skipped all the odd values from 0 to 100. whenever continue is executed, it skips everything after that and moves to the next iteration. This is why we can’t see the output which is just after that, which says even number and then prints the number.

So, this was about the break and the continued keywords. Both the keywords are very useful and interesting. The break keyword is used to break out of the loop, and the continue keyword is used to skip that particular iteration over some condition, just as we saw above. We can often use those keywords in our programs, as and when required.

So, wrapping up, we are using the break and the continue keyword to interrupt the flow of the loop, by either breaking out of the loop or by skipping some particular iteration(just as shown above, in the case of odd numbers).