1

I was always aware of labels in Java to use for loops such as:

myLoop: for(;;) {
  // codez
  break myLoop;
}

but just recenlty I found out that this is valid:

myLabel: System.out.println("");

Why would one want to do that? What is the use of this (if any)?

Lucas
  • 3,181
  • 4
  • 26
  • 45

1 Answers1

1

The label at the top of a control structure causes execution to resume at the end of the control structure once break myLoop; is called.

Putting a label on a line that doesn't precede a control structure doesn't do anything. There's no point, but at least it's harmless.

Labels are described here in the Java language specification. There's nothing stopping you from putting a label on any statement. Maybe Java's designers didn't want to restrict which statements could be labeled so that if they introduced a new control structure they wouldn't have to add it to the set of statements that can be labeled.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276