Java continue Keyword

The Java continue statement skips the current iteration of a for loop, while loop, or do-while loop and moves to the next iteration. The usage of continue keyword is very similar to break keyword, the latter terminates the loop itself.

1. Syntax

The syntax of continue statement is very straightforward. We can use it inside a loop, either with a label or without a label.

while (testExpression) {
  //statement(s)
  
  if(continue-condition)
    continue;

  //statement(s)
}

//statement(s)

In the above example, when the continue-condition evaluates to true then continue statement terminates the current iteration and control is passed to the testExpression in the beginning of the while loop.

2. Type of continue Statements

There are two forms of the continue statements:

The unlabeled continue statement skips to the end of the innermost loop’s body and evaluates the condition expression that controls the loop. In more general terms, continue skips the statements after the continue statement and keeps looping.

for (initialization; condition; update) {
  
  //statement(s)
  for (initialization; condition; update) {
    //statement(s)
    
    if(continue-condition)
      continue;

    //statement(s)
  }
}

On the other hand, a labeled continue statement skips the current iteration of a loop marked with the given label. In the following example, the control is moved to the outer loop when the continue statement is executed.

label outer_loop;
for (initialization; condition; update) {
  
  //statement(s)
  label inner_loop;
  for (initialization; condition; update) {
    //statement(s)
    
    if(continue-condition)
      continue inner_loop;

    //statement(s)
  }
}

3. Continue Keyword Example

Let’s look at one example to understand better continue statements in Java. The program uses a for loop to iterate over numbers from 0 to 9.

  • If the number is even, the iteration is skipped using the continue statement.
  • If the number is odd, it is printed in the console.
for( int i = 0 ; i < 10 ; i++ ) {

  if( i % 2 == 0) {
    continue;    //if i is even, skip the current iteration
  }

  System.out.println("The number is " + i );
}

The program output is:

The number is 1
The number is 3
The number is 5
The number is 7
The number is 9

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial