Search code examples
javabreak

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?


Solution

  • 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, which in turn can only appear inside switch, while, do, or for statements (#14.15), or by continue statements, which in turn can only appear inside 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.