I have 2 fors, after the nested for I have some code which I don't want to execute if a condition is true inside the nested for. If I use break that code would execute, so (as I learned in SCJP) I used continue label;
for the outer for.
Is this a deprecated usage of Java ? Old fashioned ? Somebody suggested to use recursion or something else, but for me this is perfectly normal, simple, up-to-date and the perfect way of doing it.
here:
for (bla bla) {
for (bla bla) {
if (whatever) continue here;
}
// some code I don't want to execute if whatever is true
}
Thanks
Edited:
If I rephrase my question as: How can you 'navigate' between multiple nested fors ? This approach would be the 'recommended' way ? because this is what it says in SCJP Book. If not .. would this mean that Katherine Sierra
and Bert Bates
are wrong ?
Edited2:
Why is continue label;
discouraged ? I want an answer of the concepts or inside workings of OOP or Java, what might go wrong ..
The continue statement, when used in association with loops in Java, skips the remaining statements in the loop body and proceeds to the next iteration of the loop. This is in contrast to the break statements, where it escapes from the immediate loop.
What is a labeled loop in Java? A label is a valid variable name that denotes the name of the loop to where the control of execution should jump. To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the label is called a labeled loop.
The continue statement skips the current iteration of a for , while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
Java continue statement is used to skip the current iteration of a loop. Continue statement in java can be used with for , while and do-while loop.
The answer is: it depends. If you find yourself using continue
a lot then it might be a sign that your code needs a refactor. However, in the scenario you've given it seems like an OK place to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With