0
public void go(){
    String o = "";
    z:
    for (int x = 0; x<3; x++) {
        for (int y = 0; y<2;y++) {
            if (x==1) 
                break;
            if (x==2 && y==1)
                break z;
            o = o + x+y;
        }
    }

    System.out.println(o);
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34

4 Answers4

3

It a label for a directed break (or a directed continue). See comments added below:

public void go(){
    String o = "";
    z:                       // <=== Labels the loop that follows
    for (int x = 0; x<3; x++) {
        for (int y = 0; y<2;y++) {
            if (x==1) 
                break;       // <=== Not directed, only breaks the inner loop
            if (x==2 && y==1)
                break z;     // <=== Directed break, breaks the loop labelled with `z`
            o = o + x+y;
        }
    }

    System.out.println(o);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

This is a syntax a bit similar to old goto instructions. When a break occurs, you will exit from the loop right after the "z", in this case the most outer for loop. This works also with continue statements.

Slimu
  • 2,301
  • 1
  • 22
  • 28
  • 3
    It is imho entirely different from `goto`. It only allows you to specify which scope you want to `break` out of or `continue`, not arbitrary jumps like you can with `goto` – Mark Rotteveel Mar 26 '14 at 10:20
  • @MarkRotteveel I concur. A goto statement means execution will jump to a particular line. – anonymous Mar 26 '14 at 10:23
  • 1
    It is a bit similar since you jump over code that would normally be executed. Of course it can be used only with break and continue and it doesn't have the same power of jump like goto's have in some languages. – Slimu Mar 26 '14 at 10:23
  • This is almost a religion discussion since each person may think that a goto can jump anywhere so my above statement seems wrong, but on the other side, it's worth nothing that goto is just a transfer of control to another line in the program, but not like a function does. – Slimu Mar 26 '14 at 10:33
0

It's a label. You can use continue keyword to skip the current iteration and to reach to this point, also skipping the innermost loop.

Kashif Nazar
  • 20,775
  • 5
  • 29
  • 46
0

Basically it is a jump mark. See here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html (there is a jump mark called search implemented and explained)

Christian
  • 1,589
  • 1
  • 18
  • 36