While browsing questions and answers in this forum i found a piece of code were names were given to loops in order to use them for break. Like
nameofloop:
for(){
for(){
if(){ break nameofloop;}
}
}
Im new to programming and i havent seen that before. My question is what other uses of naming loops are there?
You cannot place it anywhere, only before statements (and it is only useful for statements which have other nested statements in them). (And continue label; is only possible if it was in fact a loop which got labeled.)
You can do two things. 1. Create another String but initialize it before the while loop. and then in the while loop when you are creating the new string, append the newly created string in the string created above.
This is not a labeled loop, is just a label that you place anywhere and then you can "break" or "continue" to depending on your conditions. You can also use in a nested if-else with for loopings in order to break several loops decorated with if-else, so you can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.
Its use is discouraged as resembles a goto and causes spaghetti-code.
Personally I used only once, time ago, in order to break a for loop inside other two for loops with if-else and continue in the outer loop, as break
inside a loop breaks this loop, but you continue in the outer loop, not the most-outer that was my case.
You can also say:
continue nameofloop;
...to jump to start of the named loop. I don't think there are any other use cases for labels in Java.
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