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
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
gotostatement; identifier statement labels are used withbreak(§14.15) orcontinue(§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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With