A CONTINUE statement inside a loop or iteration in Java causes the program control to go to the beginning of the loop. Next iteration of the loop continues as usual. A CONTINUE statement can be used only with Loops. If you use, you get the error "continue cannot be used outside of a loop".
There are two types of CONTINUE statements.
- CONTINUE without LABEL
- CONTINUE with LABEL
Java Continue Statement without LABEL
A CONTINUE statement without a LABEL statement can Skip remaining statements of the loop for the current iteration. It can affect only the Inner Loop or a Single Loop or the Loop where the CONTINUE statement is present.
You can use CONTINUE without label statement with the loops, FOR, WHILE, DO WHILE and FOR-EACH. You can nest any number of loops and use CONTINUE statement with a Label at any Level. The number of loops may be more than two for example.
Java Continue with LABEL Statement and Rules to Use
Usually, a CONTINUE statement is used inside an IF statement which is surrounded by a Loop with a Label.
Rules:
1. A Label name or an identifier can start with an Alphabet, Underscore ( _ ) or a Dollar ($) sign. It may contain numbers.
2. A Label should be declared before the loop which contains the CONTINUE statement.
3. You can not use CONTINUE on a Label that is outside the Loop Block. It means that LABEL loop block is different.
4. You can exit an Inner loop with CONTINUE on Label for Outer loop. Without using a Break statement, you are exiting a loop.
5. You can restart an Inner loop without affecting Loop Counter value.
Example: Continue Outer Loop with Label
class ContinueOuterLabel { public static void main(String args[]){ outer: for(int i=1; i<=5; i++) { inner: for(int j=i; j>0 ;j--) { if(i>3) continue outer; System.out.print(j +","); } System.out.println(""); } System.out.println("OUTSIDE LABEL"); } } //OUTPUT //1, //2,1, //3,2,1, //OUTSIDE LABEL
This is how a Java CONTINUE statement works with or without a LABEL.
Share this Last Minute Java Tutorial with your friends and colleagues to encourage authors.