continue (Java)
Appearance
The continue keyword works in Java in the same way that it does in the C Programming Language and also C++. When used inside of while and for loops it will skip the remaining instructions in the loop and begin on the next iteration in the loop.
The following prints only even numbers between and including 0 and 10
for (int i=0; i<=10; i++) { //skips the print statement if i is not even if(i % 2 != 0) { continue; } //prints the integer "i" followed by a space System.out.print(i + ' '); }
The result of this loop is: 0 2 4 6 8 10
If one provides a label to any loops, the continue keyword can be used to jump to the label instead much like a goto statement.
outer: for (int i = 0; i<=3; i++) { for (int j = 0; j<=3; j++){ if ((i == 2) && (j == 0)) { continue; } if ((i == 0) && (j == 2)) { continue outer; } System.out.println(i + " " + j); } }
The result of these two loops are:
0 0 0 1
i==0, j==2, skip out of the j loop completely and go to the next i
1 0 1 1 1 2 1 3
i==2, j==0, skip the j==0 loop but still try the next j
2 1 2 2 2 3 3 0 3 1 3 2 3 3