简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM