Java Break Statement - Quiz

Total: 5 questions

1. 

Where break statements can be located?

Inside loop and switch statement.

2. 

What is the syntax of a labeled break in Java, and what is a label?

The syntax is break label;. A label is any valid Java identifier followed by a colon, placed at the beginning of the block or loop it marks (for example outer:). The labeled break transfers control to the end of that labeled block. The label must be placed directly before the block or loop being exited.

3. 

What is the difference between an ordinary (unlabeled) break and a labeled break in Java?

An unlabeled break terminates only the innermost loop or switch that directly encloses it. A labeled break, break label;, exits the block or loop marked with that label, so it can leave an outer loop or a standalone labeled block, not just the nearest one.

4. 

How do you exit several nested loops at once in Java?

A plain break exits only the innermost loop. To leave several nested loops at once, put a label before the outer loop (for example outer:) and use a labeled break from the inner loop: break outer;. Alternatively, move the nested loops into a separate method and end it with return, which is often easier to read.

5. 

What does a break do if a switch statement is nested inside a loop?

An unlabeled break inside such a switch terminates only the switch, not the loop — the loop keeps running with its next iteration. To leave the loop directly from a case branch, you must use a labeled break that targets a label placed before the loop.

Page 1 of 1