Java From Beginner To Advanced

0% completed

Previous
Next
Java continue Statement

The continue statement in Java is used to skip the current iteration of a loop and proceed with the next iteration. It helps in controlling the flow within loops by bypassing specific portions of code when certain conditions are met, without terminating the entire loop.

How It Works

  • When the continue statement is executed, the rest of the code inside the loop for that iteration is skipped.
  • The loop then proceeds with the next iteration immediately.
  • It is often used in loops when you want to ignore certain values or conditions without exiting the loop completely.

Syntax

continue;
  • The continue statement is placed inside the loop's code block.
  • It does not require any value or condition along with it since it acts immediately when executed.

Example 1: Skipping a Specific Iteration in a for Loop

Below is an example that demonstrates the use of continue within a for loop. The loop prints numbers from 1 to 5 but skips the number 3.

Java
Java

. . . .

Explanation:

  • In the loop, when i equals 3, the continue statement is triggered, so the remaining code within the loop is not executed for that iteration.
  • The loop immediately moves to the next iteration, meaning 3 is not printed, while other numbers are.

Example 2: Using continue in a while Loop

Below is an example that shows how the continue statement can be used in a while loop to bypass certain conditions. In this example, odd numbers are skipped, and only even numbers are printed.

Java
Java

. . . .

Explanation:

  • The while loop iterates as long as number is less than or equal to 10.
  • If number is odd (checked using number % 2 != 0), the continue statement is executed and the remaining code for that iteration is skipped.
  • Only even numbers are printed, and the loop progresses correctly due to the increment before the continue statement.

By using the continue statement, you can fine-tune your loop's behavior by skipping unnecessary iterations under specific conditions. This helps in creating more efficient and readable code. Experiment with these examples to see how continue works within different loop structures.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next