continue keyword in Java
” continue
“ keyword is used to stop the execution of current iteration and start the execution of next iteration in loops such as for loop , while loop.
The statements after the continue keyword won’t be executed.
Example with for loop
- public class MainProgram
- {
- public static void main(String[] args)
- {
- for (int i = 1; i <= 100; i++)
- {
- if(i % 10 != 0)
- {
- continue;
- }
- System.out.println(i);
- }
- }
- }
public class MainProgram { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { if(i % 10 != 0) { continue; } System.out.println(i); } } }
In the above program,we are printing only those numbers which are divisible by 10.
If number is not divisible by 10 then continue statement is executed and it will stop further execution of code and move to the next iteration in loop.
Similarly, continue can be used in while loop
Example with while loop
The following while loop will produce a list of even numbers from 1 to 100:
- int count = 1;
- while (count <= 100) {
- if (count % 2 != 0) {
- count++;
- continue;
- }
- System.out.println(count);
- count++;
- }
int count = 1; while (count <= 100) { if (count % 2 != 0) { count++; continue; } System.out.println(count); count++; }
In the above program,we are printing only even numbers.
If number is not divisible by 2 then continue statement is executed and it will stop further execution of code and move to the next iteration in loop.
Note:
The continue keyword is used to skip the further execution of statements and start the next iteration of a for or while loop.