Language Upgrades · interview question
Which of the following is a correct use of a switch expression in Java?
Multiple choiceEasychapter-12-curatedpremiumlanguage-upgradespattern-matching
Answer and explanation
Correct answer
D. Int result = switch (value) { case 1 -> 10; case 2 -> 20; default -> 0; };
Why
The correct syntax for a switch expression uses '->' to define the result for each case, making it more concise and easier to read compared to the traditional switch statement.
Test yourself on Language Upgrades
A free test with instant, explained results. No account needed.
More Language Upgrades questions
- How can sealed classes help in managing a complex class hierarchy in an e-commerce application?
- When using a switch expression with pattern matching, what is a potential benefit compared to using multiple if-else…
- How does pattern matching for instanceof improve code readability and maintainability?
- How does pattern matching in switch expressions enhance type safety?
- In Java, how does pattern matching for 'instanceof' improve code readability?
- How would you explain a significant advantage of using Java Records over traditional Java classes when dealing with…