Continue statement can used with iteration statement (for,while,do while).
In for statement continue transfer the control to updation of loop variable. In while and do while statement continue transfer control to condition of the loop.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class ContinueStatement { public static void main(String[] s) { for (int i = 1; i <= 10; i++) { if (i == 5) { continue; } System.out.println("value of i= " + i); } System.out.println("outside loop"); } } |
When value of i is 5 then continue statement is executed and control is transferred to beginning of loop and counter variable i is incremented by one.
When i==5 then continue statement is executed and no other statement followed by continue is executed
Result
1 2 3 4 5 6 7 8 9 10 | value of i= 1 value of i= 2 value of i= 3 value of i= 4 value of i= 6 value of i= 7 value of i= 8 value of i= 9 value of i= 10 outside loop |
Continue with label
Whenever continue is used with label then control is transferred to beginning of label.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class ContinueStatementWithLabel { public static void main(String[] s) { loop: for (int i = i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { if (i == 3) { continue loop; } System.out.println("value of i = " + i + " value of j = " + j); } } System.out.println("outside loop"); } } |
Result
1 2 3 4 5 6 7 8 9 10 11 12 13 | value of i = 1 value of j = 1 value of i = 2 value of j = 1 value of i = 2 value of j = 2 value of i = 4 value of j = 1 value of i = 4 value of j = 2 value of i = 4 value of j = 3 value of i = 4 value of j = 4 value of i = 5 value of j = 1 value of i = 5 value of j = 2 value of i = 5 value of j = 3 value of i = 5 value of j = 4 value of i = 5 value of j = 5 outside loop |