Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Java search: "block"

Tags:

java

search

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

like image 316
user1357147 Avatar asked Dec 21 '25 04:12

user1357147


1 Answers

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.

like image 52
T.J. Crowder Avatar answered Dec 22 '25 18:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!