Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java label? Outer, middle, inner

Tags:

java

Please don't worry about the loop but my question is about those keywords: outer, middle, and inner.They are not declared as instance variable, why the IDE let the code compile? I did some search on google, is this java label? some kind of keywords in Java? Thanks guys.

public class LoopTest{

public static void main(String[] args){
    int counter = 0;

    outer:
    for(int i = 0; i < 3; i++){
        middle:
        for(int j = 0; j < 3; j++){
            inner:
            for(int k = 0; k < 3; k++){{            
            }
                if(k - j > 0){
                    break middle;
                }
                counter++;
            }
        }
    }
    System.out.println(counter);
}

}

like image 635
OPK Avatar asked Dec 29 '14 22:12

OPK


2 Answers

Java supports labels. This is described in this article from Oracle.

So, basically you can have loops with labels and you can use keyword continue, break and so on to control the flow of the loop.

The following sample illustrates how to use the loop with the break keyword. When break is invoked it terminates the labeled statement i.e. the statement following someLabel

someLabel:
    for (i = 0; i < 100; i++) {
        for (j = 0; j < 100; j++) {
            if (i % 20 == 0) {
                break someLabel;
            }
        }
    }

The continue keyword handles labels the same way. When you invoke e.g. continue someLabel; the outer loop will be continued.

As per this SO-question you can also do constructs like this:

BlockSegment:
if (conditionIsTrue) {
    doSomeProcessing ();
    if (resultOfProcessingIsFalse()) break BlockSegment;
    otherwiseDoSomeMoreProcessing();
    // These lines get skipped if the break statement
    // above gets executed
}
// This is where you resume execution after the break
anotherStatement();

Personally, I would never recommend using labels. Instead I find that the code gets easier to follow if you instead rearrange your code so that labels are not needed (by e.g. break out complex code to smaller functions).

like image 52
wassgren Avatar answered Oct 22 '22 16:10

wassgren


Early in Java, there was a goto operator. One day, James Gosling decided to remove it. But, it turned out there was still use in allowing you to use goto inside loops. So how to do this? Well, with named loops (also known as labeled loops) you could have all the good stuff of breaking out of loops without the downsides of goto ridden spaghetti code.

So named loops became a thing, and break and continue were allowed to break or continue a loop other than their immediate parent.

like image 23
corsiKa Avatar answered Oct 22 '22 15:10

corsiKa