What We Are Learn On This Post
Continue Java Statement: Welcome to Another new post for core Java tutorial, in the last post we have discussed the break statement in Java and this post, we are going to learn about the continue statement and how to use continue statement in your project with some simple example for better understanding. The continue statement mainly used to skip the current iteration of a loop.
What does continue do in java?
The Java continue statement has widely used the statement to control the flow of loops. It is widely used inside a loop like while loop, do-while loop, for a loop. While at the time of execution if compiler found the continue statement, then it will stop the current iteration and start a new iteration from the beginning.
This statement is helpful when you want to continue the loop. Still, you don’t want the rest of the statements after the continue statement will be executed for a particular condition. In that case, the continue statement is helpful.
Continue Java Syntax
The Syntax for continue statement looks like below:
continue;
continue word followed with a semicolon.
package java_Basics; public class Continue_Example { public static void main(String[] args) { for (int i = 1; i <= 10; ++i) { if (i > 4 && i < 9) { continue; } System.out.println(i); } } }
Example:
1 2 3 4 9 10
Labelled continue Statement
Whatever continue statements we have discussed till now that’s all are unlabelled continue statement. During the execution, if the java compiler found the continue statement, then it skips the statements those are present after the continue statements of a loop (while,do-while, for-loop).
There is another form of continue statement that’s called labelled continue statement. That can be used to skip the execution of statements that lies inside an outer loop.
class LabeledContinue { public static void main(String[] args) { label: for (int i = 1; i < 6; ++i) { for (int j = 1; j < 5; ++j) { if (i == 3 || j == 2) continue label; System.out.println("i = " + i + "; j = " + j); } } } }
Note: The use of labelled continue is discouraged because by using this, it’s tough to understand the flow of execution. So in our point of view if there is a situation where you need to implement the labelled continue statement that time tries to refactor your code and try to solve in a different way to make it more readable. Because if you are using labelled continue statement then the that will create ambiguity situation.
Continue Java Important Points
Here below are some important points about the continue statement:
- In simple cases, we can replace the continue statement with an if-else condition. If there are multiple if-else conditions that time, it’s better to use continue statement for making your codes more readable.
Ref: article
Leave a Reply