Continue statement in Java is used to force the iteration of the loop. As soon as a continue statement is encountered in a loop, remaining statements in the loop that follow the continue statement are not executed and the control jumps to the next iteration of the loop.
What happens after the control jumps to the beginning of the loop differs based on the type of loop used.
- For while loop and do-while loop, continue statement causes the transfer of control to the condition of the loop.
- In case of for loop, continue statement causes the transfer of control initially to the increment part of the for loop and then to the condition that controls the loop.
Java continue statement examples
1- Using continue statement in a for loop to print only odd numbers between 1-10.public class ContinueDemo { public static void main(String[] args) { for(int i = 0; i <=10; i++){ // even case don't print the number // go to next iteration if(i%2 == 0) continue; System.out.println(i); } } }Output
1 3 5 7 92- Here is another example using continue statement with while loop. In the example user is prompted to enter a number until a positive integer is entered. When a positive integer is entered control breaks out of the loop.
public class ContinueDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number; while(true){ System.out.print("Enter a number: "); number = scanner.nextInt(); if(number < 0) continue; if(number > 0){ System.out.print("Entered number is: " + number); scanner.close(); break; } } } }Output
Enter a number: -5 Enter a number: -10 Enter a number: 6 Entered number is: 6
Labelled continue statement in Java
Just like break statement, continue statement can also be labelled to specify which specific loop has to be iterated.
For labeling a loop you just put a label (any name) in the starting of the loop followed by a colon. To continue iterating that labelled loop you will use the following statement.
continue label_name;
Java labelled continue statement example
public class ContinueDemo { public static void main(String[] args) { outer: for (int i=1; i<4; i++) { for(int j=1; j<10; j++) { if(j == 3) continue outer; System.out.println(j); } } } }Output
1 2 1 2 1 2That's all for the topic Java Continue Statement With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Initializer Block in Java
- Java Conditional Operators With Examples
- Java Collections Framework Tutorial
- HashSet Vs LinkedHashSet Vs TreeSet in Java
- Covariant Return Type in Java
- How to Write to a File in Java
- Display Time in 12 Hour Format With AM/PM in Java
- Introduction to Hadoop Distributed File System (HDFS)
No comments:
Post a Comment