# Java Continue Keyword

This Java example uses the continue keyword in a while-loop to skip to the next iteration of the loop. Continue does not terminate the loop.**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**Continue:** 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.

**Java program that uses continue keyword**
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++;
}
}
}
**Output**
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**Java program that causes infinite looping**
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.

SwitchCase

**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."

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.