Java Reference ยท Keywords and Statements
Java labeled statements
Reference for Java labeled statements: how a label names a loop or block, how labeled break and continue leave nested loops, and when to avoid them.
A label is an identifier followed by a colon placed in front of a statement. Its only purpose in modern Java is to give a name to a loop (or a block) so that break or continue inside a nested loop can refer to an outer one. There is no goto in Java; goto is a reserved word that is not used.
Without a label, break and continue always act on the innermost loop (or switch). With a label, they act on the labeled statement.
outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 2) continue outer; // next i if (i == 2) break outer; // leave both loops } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
label: statement break label; continue label;
| Statement | Effect |
|---|---|
label: for/while/do ... |
Names the loop. |
break label; |
Ends the labeled statement (loop, block, or switch) and continues after it. |
continue label; |
Skips the rest of the current iteration of the labeled loop and starts its next iteration. The label must name a loop. |
label: { ... } |
Names a block; only break label; is meaningful. |
Usage notes
- The label must be visible:
break labelandcontinue labelhave to appear inside the statement they name. You cannot jump to a label elsewhere in the method, so there is no spaghettigoto. - Same name twice: a label cannot be reused inside its own scope, but separate loops may use the same name one after another.
- Naming: labels are identifiers; the convention is lowercase (or UPPER_CASE in older code) with a meaningful name such as
searchornextCandidate. continuein aforloop runs the update expression (i++) before the next test. For a labeledcontinue, that happens for the labeled loop.- Alternatives: often a small method with
returnis clearer than a label. Searching a grid becomesint[] find(int[][] grid, int target)that returns the position directly, which also avoids the mutablefoundvariables. - Streams and lambdas: a label cannot cross a lambda boundary; inside
forEachabreakis impossible. Use a plain loop ortakeWhile/anyMatchinstead. - Try/finally: a labeled
breakthat leaves atryblock still runs itsfinallyblock. - Readability: one or two labeled loops are fine; if you need many, restructure the code.
Related
breakandcontinue,for,whileanddo-while,return- Lessons: Break and continue, For loops