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);
}
Asked
Active
Viewed 1,226 times
0

Michael M.
- 10,486
- 9
- 18
- 34

user3463561
- 1
- 2
-
here's some more info on [brancing statements in java](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html) – soulcheck Mar 26 '14 at 10:18
-
It's basically a goto. See: http://stackoverflow.com/questions/2430782/alternative-to-a-goto-statement-in-java – Kuchi Mar 26 '14 at 10:19
-
Spaghetti code ensues. – Mr. Polywhirl Mar 26 '14 at 10:20
-
Also more info here: http://stackoverflow.com/questions/12070942/whats-the-point-of-using-labeled-statements-in-java – Averroes Mar 26 '14 at 10:22
-
check this out too : http://stackoverflow.com/questions/5057931/using-labels-in-java-without-loops – Sikorski Mar 26 '14 at 10:22
4 Answers
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
-
3It 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
-
1It 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