labels

 

  Labels have the same naming rules as variables, except for their ending colon.  See identifiers.

 

  You cannot create a freestanding label.  Labels must go on a statement.

 

  You cannot put a label on a declaration statement - only on flow control statements like if, for, whilež and do.  i.e.

The following code will not compile.  The label must go on the for statement:

 

label: int x = 0;

for ( ;  x < 3;  x++ ) {

if (x == 1) { System.out.print( x ); break; }

if (x == 2) {  break label; }

}

 

  You can repeat statement label names in a Java program, as long as they are not nested.  i.e.

This snippet containing identical labels compiles and runs successfully.

 

labelA:  for (int x = 0; x < 3; x++ ) {

if (x == 1) break label1;

System.out.println(x);

}

labelA:  switch ( x ) {

case 0: break label1;

}