This keyword stops control flow in the current iteration. It does not terminate the enclosing loop completely—it just moves to the next iteration.
In while-true
loops, continue can be used to simply our code style. We can check for conditions and then continue to the next iteration if no further processing is needed.
This program uses a while
-loop that keeps iterating until the count variable reaches 10. We generate a random int
with nextInt()
.
System.out.println
) 10 numbers that are not evenly divisible by 2 or 3.import java.util.Random; public class Program { public static void main(String[] args) { Random random = new Random(); int count = 0; // Use while-loop until count reaches 10. while (count < 10) { // Get random number. // ... Can be 0 through 9 inclusive. // ... Bound argument (10) is exclusive. int value = random.nextInt(10); // Continue to next iteration if value is divisible by 2. if (value % 2 == 0) { continue; } // Check for 3. if (value % 3 == 0) { continue; } // Print result. System.out.println("Not divisible by 2 or 3: " + value); count++; } } }Not divisible by 2 or 3: 7 Not divisible by 2 or 3: 7 Not divisible by 2 or 3: 7 Not divisible by 2 or 3: 1 Not divisible by 2 or 3: 5 Not divisible by 2 or 3: 5 Not divisible by 2 or 3: 1 Not divisible by 2 or 3: 1 Not divisible by 2 or 3: 7 Not divisible by 2 or 3: 1
Continue may sometimes be involved in infinite loop problems. In while-true
loops, or loops with continue, be sure to verify that the loop terminates in all situations.
public class Program { public static void main(String[] args) { while (true) { continue; } } }
switch
The continue keyword can be used in a switch
case. This causes control flow to exit the case of the switch
. The following case is not reached.
A "break
" statement terminates the entire enclosing loop—no further iterations are processed. A "continue" just stops the current iteration and moves to the next.
With continue, we modify control flow to stop the current iteration only. Control flow, which pushes forward like a river in a program, is diverted temporarily with "continue."