Arrow labels in a switch statement
Since Java 14, switch can be an expression that produces a value, and case X -> arrow labels never fall through. The compiler checks that a switch expression covers every possible input, and Java 21 adds pattern matching, guards and case null on top.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite the month-length switch from Topic 2.3 as a switch expression with arrow labels, and print the lengths for months 2, 4 and 12.
Write a switch expression that maps a traffic light enum (RED, YELLOW, GREEN) to the seconds until change (30, 5, 25), with no default. Print all three.
Using a switch expression on a String command ("add", "sub", "mul") compute the result for a = 6 and b = 3; for anything else, yield 0 from a block that also prints unknown command. Test with "mul" and "pow".
Explain it without notes
What are the differences between case X: and case X ->?
Why can't you use return to give a switch expression its value, and what do you use instead?
What does exhaustive mean for a switch expression, and why is it better to list every enum constant than to add a default?
What did Java 21 add to switch?
Expected output
1: weekday
6: weekend
9: not a day