SoFunction
Updated on 2025-03-08

Use labels in Java to control the execution process of a loop

1. Preface

java and label are two completely unrelated words, and today I connected them together. Imagine a question: How to stop the external loop without using return?

2. Label introduction

2.1 Introduction to label

Label is in javaRelatively uncommon usage, Labels still have their unique advantages in some cases, especially when it is necessary to jump directly out of the external loop in a multi-layer nested loop. Although usereturnThe function of tags can be replaced to a certain extent, but the following are the reasons why tags are more appropriate in some cases:

  • Multi-layer nested loop: In multi-layer nested loops, if you need to jump out of the outer loop directly in the inner loop, usereturnIt can only end the execution of the current method, and it is not convenient to just jump out of the outer loop and keep the method continuing to execute. At this time, the tag can more directly control the execution of the external loop.
  • readability: In some cases, using tags can make the code more readable. When specific logic is needed in deep loops in nested structures, it is more intuitive to display landmarks, naming, and control loops through labels.
  • flexibility: Tags provide programmers with a more granular way to control code flow. In some cases, it may be necessary to control the termination or jump of the cycle with more precise accuracy, and the tag provides this kind of meticulous control capability.
  • Habits and routines: In some programming styles and teams, using tags to control loops is a common practice because tags can provide a way to control loops directly and clearly.

Although tags can be avoided in many cases in other ways, there is still a need to use tags to control loops more flexible and directly in specific scenarios. Therefore, when choosing whether to use tags, you need to weigh factors such as code clarity, readability, flexibility and team programming habits.

2.2 Use of label in JDK source code

Recently, I was looking at some knowledge about thread pools and found that an addWorker method is particularly interesting

private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    for (;;) {
        int c = ();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! ()))
            return false;

        for (;;) {
            int wc = workerCountOf(c);
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            if (compareAndIncrementWorkerCount(c))
                break retry;
            c = ();  // Re-read ctl
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }
    ...

There is in the source coderetry:break retry;as well ascontinue retry;These are the use of tags

2.3 Example of label in double loop

public static void main(String[] args) {
    outerLoop:
    for (int i = 0; i < 5; i++) {
        ("outer Loop: " + i);
        for (int j = 0; j < 3; j++) {
            if (j == 2) {
                break outerLoop; // Terminate external loop            }
            ("Inner Loop: " + j);
        }
    }

2.4 label principle

In Java, labels (Labels) are not essentially language structures, but rather tags at the compiler level, used to identify specific code blocks in the code, so that code flow can be controlled through tags. In the implementation of the Java compiler, the handling of tags is as follows:

  • Compilation stage: When the Java source code is compiled, the compiler will identify the tags and assign a unique identifier to each tag.
  • Generate bytecode: When the compiler converts the source code to Java bytecode, it will add support for tags to the bytecode. Specifically, in the generated bytecode, the tag will be converted into jump instructions to implement the jump function.
  • Runtime execution: When the program is running, the Java virtual machine (JVM) will execute the code according to the jump instructions in the bytecode, including processing the jump of the tag.
  • Control flow jump: When executing a code block with a tag, the jump instruction implemented by the tag allows the program to jump to a specified position during execution to control the process of the code.

Although tags in Java provide a mechanism for jumping in loops and code blocks, because their use is not common and easily leads to a decrease in code readability, it is generally recommended to avoid over-dependence on tags in normal programming. In most cases, traditional control flow statements are used (e.g.breakandcontinue) can express logic more clearly and avoid introducing unnecessary complexity.

In general, a tag is a jump tag implemented at the Java compiler level. It realizes control flow jumps during program execution by converting it into corresponding jump instructions in bytecode.

2.5 Other languages ​​with label

In programming languages, some languages ​​support the use of labels to identify code blocks, thereby implementing jumps and control processes. Here are some common programming languages ​​that support tags:

  • Java:Java is a tag-enabled language. In Java, you can use tags to identify loops and code blocks to achieve jumps in nested structures.
  • C / C++: The use of tags is also supported in C and C++. By tagging a tag before the code block, you can use labeled in a loop or conditional statementbreakorcontinueJump to a specific location.
  • Go:Go language also supports tags. In Go, tags are usually used with loops or selection statements to control jumps.
  • Perl:Perl is another language that supports tags. Tags can be used in Perl to jump to specific locations in code blocks.
  • Kotlin:Kotlin is a modern programming language that supports tags. Tags are commonly used in Kotlin to control the execution flow of code blocks with nested structures.

The tagging functionality in these languages ​​can provide a flexible mechanism for implementing jumps and control processes between different code blocks. When using tags, you should pay attention to following best practices to ensure the readability and maintenance of the code.

3. Summary

Tags are a mechanism for controlling process jumps in Java, especially when external loops need to be jumped out of multi-layer nested loops. It can improve the readability and flexibility of the code, but overuse may lead to increased code complexity and reduce maintainability.

The above is the detailed content of using labels (labels) in Java to control the execution process. For more information about Java labels (labels) controlling loops, please pay attention to my other related articles!