continue
statement is one of the different control statements which we use very often.If continue statement is found in loop, it will continue the current iteration and will not execute statements following continue statements. It is generally used to skip current iteration
on the basis of some condition.
Table of Contents
Java continue statement example
You have elements in the array from 1 to 10 but you want to print only odd numbers and skip even numbers. In this case, if we get an even number, we will skip that iteration so loop
won’t print even number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class ContinueStatementExample { public static void main(String[] args) { int arr[] ={1,2,3,4,5,6,7,8,9,10}; for (int i = 0; i < arr.length; i++) { if(arr[i]%2==0) { continue; } System.out.print(" "+arr[i]); } } } |
When you run above program, you will get below output:
Labeled continue statement
Labeled break continue
is used when you want to continue labeled for loop rather than current loop.
For example:
You have a two-dimensional matrix that contains only 0 and 1. You want to skip a row if the row starts with 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package org.arpit.java2blog; public class LabeledContinueStatment { public static void main(String[] args) { int[][] arr = { { 1, 0, 0 }, { 0, 0, 0 }, { 1, 1, 1 }, { 0, 1, 1 } }; outer: for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][0] == 1) { System.out.println("Skipping row "+i+ "as it started with 1"); continue outer; } System.out.print(" " + arr[i][j]); } System.out.println(); } } } |
When you run above program, you will get below output:
0 0 0
Skipping row 2as it started with 1
0 1 1
That’s all about Java continue statement example.