Java for-loop, do i need continue statement here?
Consider this code:
if (int a == 0) {
开发者_开发问答 System.out.println("hello");
continue;
}
This if
is part of a for
loop in java. What is the significane of continue statement here? I know continue
is the opposite of break
so that it wont break out of the loop rather just skip that iteration for anything below it. But in case it is inside an if
statement, do I really need it like this?
No, you don't need to use continue
there, you can use an else
block instead:
if (a == 0) {
System.out.println("hello");
} else {
// The rest of the loop body goes here.
}
Which is better is a style issue. Sometimes one is better, sometimes the other - it depends on what the typical flow should be and which flow you want to emphasize in the code.
If this is the last statement of the for
loop - no, you don't need it. Otherwise you need it to skip everything below the if
-clause. If you don't want to skip it, then don't use continue
.
Here is an explanation with examples of what continue
is doing.
continue
means that the statements below the if
block won't work. If this is the behavior you need, you should continue
. Otherwise it is not needed.
精彩评论