简体   繁体   中英

How do you use the label statement in java?

According to the java book I am reading right now, you can use labels with the following types of statements:

  • A code block defined using {}
  • All looping statements (for, enhanced for, while, do-while)
  • Conditional constructs (if and switch)
  • Expressions
  • Assignments
  • return statements
  • try blocks
  • throw statements

I understand how to use them with constructs that have curly braces but what are some useful examples of using them with the other kind of statements, like expressions, assignments, return statements and throw statements?

How do you use the label statement in Java?

It isn't a statement. It is an optional attribute of an executable statement.

According to the java book I am reading right now, you can use labels with the following types of statements ...

Your book is wrong. According to the Java Language Specification #14.7 , any statement can have a label. However they can only be referenced by break statements in conjunction with switch, while, do, or for statements (#14.15), or by continue statements in conjunction with while, do, or for statements (#14.15).

what are some useful examples of using them with the other kind of statements, like expressions, assignments, return statements and throw statements?

There aren't any.

In a nested loop, for example, if you create a label for the outer loop, you can use a label statement to break out of the outer loop even if you are currently inside the inner loop. Look at my example.

OUTER_LOOP: for (int i = 0; i < 10; i++) {
             System.out.print(i + " ");
    INNER_LOOP: for (int j = 0; j < 10; j++) {
                 System.out.print(j);
                 break OUTER_LOOP;
    }
    }

There is no such thing as a useful example of label use. Apparently you are well aware of useless examples.

There is no such thing as a label use that add anything new compared to not have the label at all, when the label is not before a code block. The language chose to allow it, but using this permission is without visible effects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM