- Is breaking and continuing the only uses of labeled statements in Java?
- When have you used Labeled Statements in your programs?
Sorry the code snippet has been deleted. I am splitting the question
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
JLS 14.7 Labeled statements
(edited for clarity)
So the JLS is clear that labels are used with
breakorcontinue, and no other grammatical element of the Java programming language uses it.Strictly speaking,
breakandcontinue, labeled or not, are NEVER necessary. They can always be written out of the code. Used idiomatically, however, they can lead to more readable code.Here’s an illustrative example: given an
int[], we want to :"One (1)"on1"Two (2)"on2"Zero "on0immediately stop processing on any other number
Here we see that:
switchbreakin theswitchis used to avoid “fall-through” between casescontinue loop;is used to skip post-processing oncase 0:(the label is not necessary here)break loop;is used to terminate the loop ondefault:(the label is necessary here; otherwise it’s aswitch break)So labeled
break/continuecan also be used outside of nested loops; it can be used when aswitchis nested inside a loop. More generally, it’s used when there are potentially multiplebreak/continuetarget, and you want to choose one that is not immediately enclosing thebreak/continuestatement.Here’s another example:
Here’s another case of a labeled
breakbeing used not within an iterative statement, but rather within a simple block statement. One may argue that the labels lead to better readability; this point is subjective.And no, the last line DOES NOT give compile time error. It’s actually inspired by Java Puzzlers Puzzle 22: Dupe of URL. Unfortunately, the puzzle does not go into “proper” use of labeled statements in more depth.