Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 887
faceless1_14 Avatar asked Dec 23 '08 18:12

faceless1_14


People also ask

Does continue work in Java?

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.

How does continue work?

The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute.


2 Answers

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.

like image 149
Dustin Avatar answered Oct 18 '22 10:10

Dustin


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; 
like image 30
Diomidis Spinellis Avatar answered Oct 18 '22 09:10

Diomidis Spinellis