What is the "continue" keyword and how does it work in Java?
Asked Answered
O

12

315

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.

  • What is the continue keyword?
  • How does it work?
  • When is it used?
Orelie answered 23/12, 2008 at 18:52 Comment(0)
S
424

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;
Soliloquize answered 23/12, 2008 at 18:53 Comment(1)
I would add the caveat that if you have to use a continue keyword, then your loop is busted at a fundamental level and you will be using more memory than you need to and your loop logic is now busted.Menial
D
529

continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:

  • break terminates the loop (jumps to the code below it).

  • continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.

Dinette answered 23/12, 2008 at 18:54 Comment(0)
S
424

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;
Soliloquize answered 23/12, 2008 at 18:53 Comment(1)
I would add the caveat that if you have to use a continue keyword, then your loop is busted at a fundamental level and you will be using more memory than you need to and your loop logic is now busted.Menial
I
104

Let's see an example:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

Imine answered 23/12, 2008 at 18:56 Comment(0)
U
28

If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

This will print out only the odd numbers.

Uniocular answered 23/12, 2008 at 19:0 Comment(0)
A
16

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

Amazed answered 23/12, 2008 at 18:52 Comment(2)
I am interested in the reason why return is bad. I already have a feeling that return is bad because Scala does not encourage returns.Newsworthy
On the other hand, allowing a method to return from a deeply nested loop might be the easiest, most readable, and most reasonable way to do things, rather than creating extra variables just to make the loop exit look more clean.Wingover
C
5

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

Commutual answered 19/12, 2017 at 15:8 Comment(0)
F
4

As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).

It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.

This is why a lot of people fail to correctly answer what the following code will generate.

    Random r = new Random();
    Set<Integer> aSet= new HashSet<Integer>();
    int anInt;
    do {
        anInt = r.nextInt(10);
        if (anInt % 2 == 0)
            continue;
        System.out.println(anInt);
    } while (aSet.add(anInt));
    System.out.println(aSet);

*If your answer is that aSet will contain odd numbers only 100%... you are wrong!

Felicity answered 22/3, 2016 at 18:51 Comment(0)
H
4

Continue is a keyword in Java & it is used to skip the current iteration.

Suppose you want to print all odd numbers from 1 to 100

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

        for(int i=1 ; i<=100 ; i++) {
            if(i % 2 == 0) {
                continue;
            }
            System.out.println(i);
        }

    }
}

continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.

Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.

Howrah answered 19/4, 2019 at 9:19 Comment(0)
H
3

Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop. Consider the following Program. '

public class ContinueBreak {
    public static void main(String[] args) {
        String[] table={"aa","bb","cc","dd"};
        for(String ss:table){
            if("bb".equals(ss)){
                continue;
            }
            System.out.println(ss);
            if("cc".equals(ss)){
                break;
            }
        }
        System.out.println("Out of the loop.");
    }

}

It will print: aa cc Out of the loop.

If you use break in place of continue(After if.), it will just print aa and out of the loop.

If the condition "bb" equals ss is satisfied: For Continue: It goes to next iteration i.e. "cc".equals(ss). For Break: It comes out of the loop and prints "Out of the loop. "

Harbaugh answered 29/8, 2016 at 16:11 Comment(1)
Pretty sure it would also print cc since "cc" != "bb" and the print statement is before the breakAlkali
A
3

The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.

It can be used with for loop or while loop. The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

In case of an inner loop, it continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.

for example

class Example{
    public static void main(String args[]){
        System.out.println("Start");
        for(int i=0; i<10; i++){
            if(i==5){continue;}
            System.out.println("i : "+i);   
        }
        System.out.println("End.");
    }
}

output:

Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.

[number 5 is skip]

Albertinealbertite answered 22/3, 2020 at 7:5 Comment(0)
W
2

I'm a bit late to the party, but...

It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:

while ((buffer[i++] = readChar()) >= 0)
    continue;

In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.

It's a little more obvious than the equivalent:

while (...)
{ }

and definitely better (and safer) coding style than using an empty statement like:

while (...)
    ;
Wingover answered 21/12, 2017 at 23:38 Comment(3)
I definitely agree that it's cleaner and more readable code, but I'm not sure that I follow your argument about it being "safer" than the other option, while(statement); delimited directly using a semicolon.Thievish
@Aalok - It is safer because a lone semicolon is easy to miss visually. It's also easy to leave out accidentally, which would make the next statement following the while become the body of the while clause, and which would not be visually obvious. An explicit continue is obvious and conveys an intent that an empty statement does not.Wingover
I see, so you mean mainly from a design perspective. That makes sense. I had something underlying with the way the loop is structured in mind.Thievish
M
0

continue must be inside a loop Otherwise it showsThe error below:

Continue outside the loop

Mesoglea answered 15/9, 2019 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.