Home >Java >javaTutorial >What are Java's 'loop:' Labels and How Do They Control Nested Loops?
Java's Perplexing "loop:" Statement
While reviewing code, you may encounter a seemingly enigmatic statement: "loop:". At first glance, you may mistake it for a keyword, but closer examination reveals its true nature as a label.
What is a Label?
Labels are identifiers that can be attached to loop statements. They serve as convenient targets for break and continue statements, allowing for precise control over loop execution.
Syntax and Usage
Labels are typically placed immediately before the loop they refer to:
loop: for (...) { }
To break out of the labeled loop, use a break statement that references the label:
loop: for (...) { if (condition) { break loop; // Exit the "loop" loop } }
Similarly, the continue statement can be used with labels to skip the remaining statements in the loop and continue from the following iteration:
loop: for (...) { if (condition) { continue loop; // Skip remaining statements and start next iteration } }
Benefits of Using Labels
Labels provide greater clarity and readability in complex code where multiple loops are nested. By labeling loops, you can easily identify and control their execution flow.
Documentation and Example
As mentioned in the documentation, labels are most commonly used to control nested loops:
outer_loop: for (int i = 0; i < 10; i++) { inner_loop: for (int j = 0; j < 10; j++) { if (condition1) { // Exit outer loop break outer_loop; } if (condition2) { // Exit inner loop break inner_loop; } if (condition3) { // Exit inner loop break; } } }
The above is the detailed content of What are Java's 'loop:' Labels and How Do They Control Nested Loops?. For more information, please follow other related articles on the PHP Chinese website!