1Z0-808 practice question 15 of 30

Which statement is true about the switch statement?

Full set: 224 questions
Answer options
A: It must contain the default section.
B: The break statement, at the end of each case block, is optional. Correct answer
C: Its case label literals can be changed at runtime.
D: Its expression must evaluate to a collection of values.
Correct Answer:
B. The break statement, at the end of each case block, is optional.
Explanation

The switch statement evaluates an expression and executes code blocks based on matching case labels. The break statement is used to exit the switch block. If a break is omitted from a case, execution "falls through" to the next case block. This behavior is intentional and well-defined, making the break statement optional. The other statements describe incorrect constraints or behaviors of the switch statement.

Why Incorrect

A. It must contain the default section.: The default section is optional. It executes only if no other case label matches the expression's value.
C. Its case label literals can be changed at runtime.: Case labels must be compile-time constant expressions of a type compatible with the switch expression.
D. Its expression must evaluate to a collection of values.: The switch expression must evaluate to a single value of type char, byte, short, int, String, or an enum.

References

- The Java® Language Specification, Java SE 8 Edition, Section 14.11, "The switch Statement". It details the syntax and semantics, including the optional nature of break and default.

- Oracle, The Java™ Tutorials, "The switch Statement". This guide explicitly states, "The break statements are necessary because without them, statements in switch blocks fall through...". This implies they can be omitted to achieve fall-through.

Scroll to Top