Command Palette

Search for a command to run...

Back to the lesson: Topic 2.4 — Switch Expressions and Arrow Labels
Core Java · Example 4 of 4 Java 21+

Pattern matching for switch

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.

01

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.

02

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.

03

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

01

What are the differences between case X: and case X ->?

02

Why can't you use return to give a switch expression its value, and what do you use instead?

03

What does exhaustive mean for a switch expression, and why is it better to list every enum constant than to add a default?

04

What did Java 21 add to switch?

Pattern matching for switch Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

nothing
big number 500
number 7
empty text
text of length 5
something else: Double