Switch Expressions — Concept Check
Questions on Switch Expressions. Switch expressions (Java 14+) return values, use arrow syntax, and eliminate fall-through bugs from traditional switch statements.
Questions in this quiz
7 questions on Switch Expressions — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.In Java, what happens if you omit the 'yield' keyword in a block body of a switch expression?
- AThe switch expression will not compile.
- BThe switch expression will return the last evaluated expression.
- CThe switch expression will fall through to the next case.
- DThe switch expression will return null.
2.A developer uses a switch expression with multiple labels per case. What is the benefit of this approach?
- AIt increases verbosity with additional break statements.
- BIt requires a default case to handle all possibilities.
- CIt simplifies code by avoiding repeated logic.
- DIt allows fall-through behavior.
3.Given a switch expression with the arrow syntax, what is the result of missing a 'default' case?
- AThe switch expression will fall back to a default value.
- BThe code will not compile if not all cases are covered.
- CThe switch expression will always return null.
- DThe switch expression will throw a runtime exception.
4.Why might a developer prefer using switch expressions over traditional switch statements?
- ASwitch expressions can return a value directly.
- BSwitch expressions are only available in Java 8.
- CSwitch expressions require more verbose break statements.
- DSwitch expressions allow fall-through between cases.
5.A Java method uses a switch expression to map days to activities. What is a potential issue if a day is not covered by any case?
- AThe method will throw an IllegalArgumentException.
- BThe method will automatically map to a default activity.
- CThe method will return null.
- DThe method will compile but behave unpredictably.
6.How does the arrow syntax in switch expressions improve code clarity?
- ABy enabling nested switch expressions.
- BBy making the intent clear and preventing fall-through.
- CBy eliminating the need for a default case.
- DBy allowing multiple expressions per case.
7.What is the role of 'yield' in a switch expression with a block body?
- AIt allows multiple values to be returned.
- BIt exits the switch and provides a result.
- CIt continues execution to the next case.
- DIt specifies a default return value.