Home »
Java Programs »
Java Basic Programs
Java program to demonstrate the continue statement with while and for loops
Here, we are demonstrating the use of continue statement with while and for loops.
Submitted by Nidhi, on March 09, 2022
Problem statement
In Java, the continue statement is used with loops. When we need to jump to the next iteration of the loop immediately. It can be used with for loop, do while loop, or while loop.
In this program, we will use the continue statement with while and for loops. The continue statement is used to skip the below statements in the loop body.
Java program to demonstrate the continue statement with while and for loops
The source code to demonstrate the continue statement with while and for loops is given below. The given program is compiled and executed successfully.
// Java program to demonstrate the continue statement
// with while and for loops
public class Main {
public static void main(String[] args) {
int cnt = 0;
while (cnt <= 9) {
cnt = cnt + 1;
if (cnt == 5) {
continue;
}
System.out.print(cnt + " ");
}
System.out.println();
for (cnt = 1; cnt <= 10; cnt++) {
if (cnt == 5) {
continue;
}
System.out.print(cnt + " ");
}
}
}
Output
1 2 3 4 6 7 8 9 10
1 2 3 4 6 7 8 9 10
Explanation
In the above program, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we used the continue statement with while and for loop to skip the below statements in the loop body when the value of the cnt variable is equal to 5.
Java Basic Programs »