1
0

Labeled Loops in Java

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break statement can terminate the outer loop with which the label is associated. The following program, BreakWithLabelDemo, is similar to the previous program but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled “search”):

Program to demonstrate the labeled break statement.

class BeakWithLabelDemo
{
    public static void main(String[] args)
    {
        int[][] arrayOfInts = {{32, 87, 3, 589}, {12, 1076, 2000, 8}, {622, 127, 77, 955}};
        int searchfor = 12;
        int i;
        int j = 0;
        boolean foundIt = false;
        search: for(i=0; i<arrayOfInts.length; i++)
        {
            for(j=0; j<arrayOfInts[i].length; j++)
            {
                if(arrayOfInts[i][j] == searchfor)
                {
                    foundIt = true;
                    break search; // Labeled break
                }
            }
        }
        if(foundIt)
        {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        }
        else{
            System.out.println(searchfor + " not in the array");
        }
    }
}

Output

Found 12 at 1, 0

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. The control is transferred to the statement immediately following the labeled (terminated) looping statement.

A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.

Program to demonstrate the labeled continue statement.

class ContinueWithLabelDemo
{
    public static void main(String[] args)
    {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;
        int max = searchMe.length() - substring.length();
        test:for(int i=0; i<=max; i++)
        {
            int n = substring.length();
            int j = i;
            int k = 0;
            while(n-- != 0)
            {
                if(searchMe.charAt(j++) != substring.charAt(k++))
                {
                    continue test;
                }
            }
            foundIt = true;
            break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

Output

Found it

Leave a Reply