Labeled Loop in Java
In programming, a loop is a sequence of instructions that is continually repeated until a certain condition is met. In this section, we will discuss the labeled loop in Java with examples.
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.
In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good habit to label a loop when using a nested loop. We can also use labels with continue and break statements.
There are three types of loop in Java:
Let's discuss the above three loops with labels.
Java Labeled for Loop
Labeling a for loop is useful when we want to break or continue a specific for loop according to requirement. If we put a break statement inside an inner for loop, the compiler will jump out from the inner loop and continue with the outer loop again.
What if we need to jump out from the outer loop using the break statement given inside the inner loop? The answer is, we should define the label along with the colon(:) sign before the loop.
Let's see an example of labeled for-loop.
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
Java Labeled while Loop
outer value of i= 0 inner value of i= 1, j= 0 outer value of i= 1 outer value of i= 2 outer value of i= 3 outer value of i= 4
Next TopicLombok Java