Home
Java
continue Keyword
This page was last reviewed on Jan 24, 2024.
Dot Net Perls
Continue. 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.
An example. This program uses a while-loop that keeps iterating until the count variable reaches 10. We generate a random int with nextInt().
Random
Then We move to the next iteration of the loop if the value is evenly divisible by 2 or 3. We use a modulo division test.
Modulo
Result We print (with 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
Infinite loops. 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.
while
public class Program { public static void main(String[] args) { while (true) { continue; } } }
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.
switch
case
A discussion. 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.
break
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."
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 24, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.