Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java continue at the end of if

I have some example code from a book and the author is always using an continue at the end of an if.

Example:

int a = 5;
if(a == 5)
{
// some code
continue;
}

Now for me this doesn't make any sense. Might there be some kind of quality management reasoning behind it or am I just missing some bigger point?

like image 290
John Frost Avatar asked Nov 09 '12 16:11

John Frost


2 Answers

Maybe that snippet of code was inside a loop (for/while/do...while)? otherwise it does not make any sense to put a continue inside a conditional statement.

As a matter of fact, an orphaned continue (e.g.: one that is not nested somewhere inside a loop statement) will produce a continue cannot be used outside of a loop error at compile time.

like image 152
Óscar López Avatar answered Oct 21 '22 14:10

Óscar López


Continue is used to go to the next iteration of a loop. So something like this would make sense. Now you could use what ever conditions (yours is a==5 to break on), and whatever business logic you wanted (mine is a silly, contrived example).

StringBuilder sb = new StringBuilder();
for(String str : strings) {
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    str = str.substring(1);
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    str = str.substring(1);
    sb.append(str);
    if(str.length() == 0) continue; // next loop if empty

    sb.append(str);
}
like image 5
corsiKa Avatar answered Oct 21 '22 14:10

corsiKa