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?
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.Officially, I believe this is called a "labeled break". It's useful for breaking out of nested loops, such as:
I don't think it's useful for anything else.
I think it's the only case it's used. And it's not something which is commonly used, because it's usually more readable to change the value of a flag to end a loop prematurely.
Create an array (
int
) of size 10.Let the user assign the values - (use for-loop).
Find the total and average of the values stored in the array - (use for- loop).
It's known as a labelled break which is a form of branching statement. You can see all the examples in the Official Documention.
You can also say:
...to jump to start of the named loop. I don't think there are any other use cases for labels in Java.