Break

labelled-break statements

Reference -> http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=040303&p=1

A sample code:

public class TestLabelledBreak
{
    public static void main(String[] args)
    {
        callCodeOfSeemaSharma();
        callCodeOfChinni();
    }
    public static void callCodeOfSeemaSharma()
    {
        int i = 0, j = 5;
        tp: for (; ;)
        {
            i++;
            for (; ;)
            {
                if(i > --j)
                {
                    break tp;
                }
            }
            System.out.println("i =" + i + ", j = " + j);
        }
    }
    public static void callCodeOfChinni()
    {
        int i = 0, j = 5;
        tp: for ( ; ; )
        {
            i++;
            for ( ; ; )
            {
                if(i > --j)
                {
                    break tp;
                }
                System.out.println("i =" + i + ", j = " + j);
            }
        }
    }
}

Output:
First code gives an compiler error saying that "sop" is unreachable!
The second method compiles and executes fine.

Reason:
Look out the labelled break. As its breaking from the outer loop and the SOP is present inside the inner loop it may never get executed. Whereas in case 2, the SOP is present inside the if loop but not inside the inner loop. so it will get executed even when the loop breaks.

**to visit: **
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=040440
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=040412
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=023719
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=78&t=002894
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=018328&p=1

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.