Java continue Statement

h‮tt‬ps://www.theitroad.com

In Java, the continue statement is used to skip the current iteration of a loop and continue with the next iteration. When a continue statement is encountered in a loop, the control immediately goes back to the loop condition, and if it is true, the loop continues with the next iteration, skipping any remaining code in the loop body.

Here's the basic syntax of the continue statement in Java:

continue;

The continue statement can be used in loops such as for, while, and do-while loops, as well as in switch statements.

In a for loop, the continue statement is often used to skip over certain iterations based on a condition. For example, the following code uses a for loop to iterate over an array of integers and continues with the next iteration if a number is odd:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 != 0) {
        continue;
    }
    System.out.println(numbers[i]);
}

In this code, the loop iterates over the array of integers and prints out only the even numbers. When the loop encounters an odd number, it executes the continue statement, which skips the rest of the loop body and goes back to the loop condition, starting the next iteration.

In a while loop, the continue statement is used in a similar way to skip certain iterations based on a condition. For example, the following code uses a while loop to read integers from the console until the user enters a negative number:

Scanner scanner = new Scanner(System.in);
while (true) {
    int number = scanner.nextInt();
    if (number < 0) {
        break;
    }
    if (number % 2 != 0) {
        continue;
    }
    System.out.println(number + " is even");
}

In this code, the loop reads integers from the console and prints out only the even numbers until the user enters a negative number. When an odd number is entered, the continue statement skips the System.out.println statement and goes back to the loop condition, waiting for the next integer input.