2

Has anyone ever seen the following in Java?

public void methodName(){ 
   search:
     for(Type[] t : Type[] to){
       do something...
   }
}

Can someone point me to documentation on the use of "search:" in this context? Searching for "search:" has not been productive.

Thanks

  • Where did you see this in the first place? – Jon Egeland Apr 25 '12 at 20:31
  • 1
    It's a label; yes, I've seen them. They're relatively uncommon, but occasionally quite useful. They can also be used with `continue`, although all the answers so far only mention `break`. – Dave Newton Apr 25 '12 at 20:31
  • This would be of use to you if you wish to use labels in the future: [http://stackoverflow.com/q/205458/1079354](http://stackoverflow.com/q/205458/1079354). – Makoto Apr 25 '12 at 20:32

3 Answers3

12

It's a label. From §14.7 of the Java Language specification:

Statements may have label prefixes...

(Boring grammar omitted, pain to mark up)

Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

One place you frequently see labels is in nested loops, where you may want to break out of both loops early:

void foo() {
    int i, j;

    outerLoop:                     // <== label
    for (i = 0; i < 100; ++i) {
        innerLoop:                 // <== another label
        for (j = 0; j < 100; ++j) {
            if (/*...someCondition...*/) {
                break outerLoop;   // <== use the label
            }
        }
    }
}

Normally that break in the inner loop would break just the inner loop, but not the outer one. But because it's a directed break using a label, it breaks the outer loop.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

This is an example of a labelled loop.

It allows you to break or continue the target loop instead of your current loop.

Outer:
    for(int intOuter=0; intOuter < intArray.length ; intOuter++)
    {
      Inner:
      for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
      {
        if(intArray[intOuter][intInner] == 30)
        {
          blnFound = true;
          break Outer; // this line breaks the outer loop instead of the inner loop.
        }  

      }
    }

example taken from : http://www.java-examples.com/java-break-statement-label-example

Colin D
  • 5,641
  • 1
  • 23
  • 35
0

It is a Java label as defined here in JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#78994

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117