8

Somewhere going through java good articles, I found that such code compiles perfectly.

public int myMethod(){
    http://www.google.com
    return 1;
}

description says that http: word will be treated as label and //www.google.com as comment

I am not getting how Java Label is useful outside loop? Under what situation Java Label outside loop should be used?

Jayesh
  • 6,047
  • 13
  • 49
  • 81
  • It shouldn't be used outside of the loops if avoidable. Not part of the java mindset, anyway, because it introduces complexity. Like having multiple returns in a function. – iajrz Nov 07 '13 at 13:02

2 Answers2

16

Here is one benefit of using labels in Java:

block:
{
    // some code

    if(condition) break block;

    // rest of code that won't be executed if condition is true
}

Another usage with nested-loops:

outterLoop: for(int i = 0; i < 10; i++)
{
    while(condition)
    {
        // some code

        if(someConditon) break outterLoop; // break the for-loop
        if(anotherConditon) break; // break the while-loop

        // another code
    }

    // more code
}

or:

outterLoop: for(int i = 0; i < 10; i++)
{
    while(condition)
    {
        // some code

        if(someConditon) continue outterLoop; // go to the next iteration of the for-loop
        if(anotherConditon) continue; // go to the next iteration of the while-loop

        // another code
    }

    // more code
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
-1

Just because it compiles does not mean it is useful.....

Labels are often overlooked in Java (who uses labelled break, and continue ...? ). But, just because the label is not used does not mean it is illegal.

rolfl
  • 17,539
  • 7
  • 42
  • 76