Java: Using a labeled break statement

Profile picture for user arilio666

Java label statements are used to prefix that particular label to an identifier. A label can be generally used with the continue and break statements to show and prefix the code more precisely on what is happening.

A label is simply an identifier followed by a colon (:).

So that normally when we use a label we can understand what is happening inside the code block with the label name and also act as a tag to break the block using its name.

Think of it as an alias name that is used for the whole block of the code. We will see how we can break loops with for and while loop.

Syntax

labelname: statements

Example: Label Break Using For Loop

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        label1:
        for (int i = 0; i < 5; i++)
        {
            System.out.println("Value of i: " +i);
            if (i == 2)
            {
                break label1;
            }
        }
    }
}

Output:

Value of i: 0
Value of i: 1
Value of i: 2
  • Here we have used a simple for loop with an iteration of when it reaches 2. The loop should break.
  • Here as we can see I have used the label name label1 where I used it as an alias to break the loop after it reaches 2. so that when it reaches and satisfies the condition the loop breaks as we call the label name and tell it to break.

Example: Label Break Using While Loop

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        int x = 10;
        
        label1:
        while (x < 15)
        {
            if(x == 12)
                break label1;
            
            System.out.println("Value Of x: " +x);
            x++;
        }
    }
}

Output:

Value Of x: 10
Value Of x: 11

In the same scenario as with the for loop here we have decided to initialize a value of 10 and iterate it until it reaches 12 and breaks the label then and there.

Tags