Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving name to a loop

Tags:

java

loops

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?

like image 423
Giannis Avatar asked Mar 29 '11 21:03

Giannis


People also ask

Can we name while loop in Java?

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.)

How do I create a different variable name while in a for loop in Java?

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.


2 Answers

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.

like image 135
David Oliván Ubieto Avatar answered Oct 04 '22 19:10

David Oliván Ubieto


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.

like image 42
Sean Avatar answered Oct 04 '22 18:10

Sean