switch on an enum
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A switch works directly on an enum: each case names one constant. With a switch expression, Java can even check that every constant is handled.
case labels use the constant's simple name
A switch on an enum chooses a branch by the constant the variable holds. Each case label is the constant's simple name, such as case UPI, because the switch already knows the enum type.
A checkout screen shows a different message for each payment mode. Write the enum variable in switch (mode) and only constant names in the cases. Both switch styles (opens in a new tab) from Basics work.
Example 1 · One message per payment mode
enum PaymentMode { UPI, CREDIT_CARD, DEBIT_CARD, CASH_ON_DELIVERY}
public class CheckoutMessageDemo { static void showMessage(PaymentMode mode) { switch (mode) { case UPI -> System.out.println("Scan the QR code to pay"); case CREDIT_CARD, DEBIT_CARD -> System.out.println("Enter your card details"); case CASH_ON_DELIVERY -> System.out.println("Keep exact change ready"); } }
public static void main(String[] args) { for (PaymentMode m : PaymentMode.values()) { System.out.print(m + ": "); showMessage(m); } }}UPI: Scan the QR code to pay CREDIT_CARD: Enter your card details DEBIT_CARD: Enter your card details CASH_ON_DELIVERY: Keep exact change ready
What this code does
switch (mode)switches on the enum variable. Each label is only a constant name, such ascase UPI.case CREDIT_CARD, DEBIT_CARDshares one branch between two constants, as withintvalues in Basics.
Writing the enum name in a label, case PaymentMode.UPI, fails on Java 17: an enum switch case label must be the unqualified name of an enumeration constant. Java 21 accepts it, but the short name works in every version. Several constants can share a branch, case CREDIT_CARD, DEBIT_CARD ->, as in switch with arrows (opens in a new tab).
A switch expression must cover every constant
An exhaustive switch expression has a branch for every possible value. On an enum, a case for every constant is enough: no default is needed, and the compiler reports an error when a constant is missing.
A fare method must return a number for every ticket class. A switch expression always gives a value, so Java checks that each constant of the enum has a case.
Example 2 · A fare from a switch expression, no default
enum TrainClass { SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class FareDemo { static int farePer100Km(TrainClass t) { return switch (t) { case SLEEPER -> 60; case AC_3_TIER -> 160; case AC_2_TIER -> 230; case AC_FIRST -> 390; }; }
public static void main(String[] args) { int km = 500; for (TrainClass t : TrainClass.values()) { System.out.println(t + ": Rs. " + farePer100Km(t) * km / 100); } }}SLEEPER: Rs. 300 AC_3_TIER: Rs. 800 AC_2_TIER: Rs. 1150 AC_FIRST: Rs. 1950
What this code does
- The switch expression returns a value for each of the four constants, so it needs no
default. - The
;after the closing}ends thereturnstatement, as with any switch expression.
Example 3 · A new constant breaks the switch, on purpose
enum TrainClass { SLEEPER, AC_ECONOMY, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class NewClassDemo { static int farePer100Km(TrainClass t) { return switch (t) { case SLEEPER -> 60; case AC_3_TIER -> 160; case AC_2_TIER -> 230; case AC_FIRST -> 390; }; }
public static void main(String[] args) { System.out.println(farePer100Km(TrainClass.AC_ECONOMY)); }}NewClassDemo.java:7: error: the switch expression does not cover all possible input values
return switch (t) {
^
1 errorWhat this code does
AC_ECONOMYwas added to the enum, but this switch has no case for it. javac points at the exact switch that needs updating.- Fix: add
case AC_ECONOMY -> 145;. Every other switch expression onTrainClassis flagged the same way.
That check pays off later. When someone adds a constant to the enum, every switch expression without default stops compiling until it handles the new value, so no place in the program can forget it.
A default branch hides new constants
A teammate adds WALLET to the payment modes. An older switch with a default branch quietly treats it like the others, with the wrong fee, and nothing warns anyone.
Example 4 · Mistake: default quietly handles a new constant
enum PaymentMode { UPI, CARD, NET_BANKING, WALLET}
public class DefaultTrapDemo { static int fee(PaymentMode m, int amount) { switch (m) { case CARD: return amount * 2 / 100; case NET_BANKING: return 10; default: return 0; } }
public static void main(String[] args) { for (PaymentMode m : PaymentMode.values()) { System.out.println(m + ": Rs. " + fee(m, 1000)); } }}UPI: Rs. 0 CARD: Rs. 20 NET_BANKING: Rs. 10 WALLET: Rs. 0
What this code does
WALLETshould cost Rs. 5, butdefaultcaught it and returned 0. The program compiled and ran without a single warning.- The wrong line looks just like the correct
UPIline, so only a customer or the accounts team would notice.
Example 5 · Fix: list every constant, no default
enum PaymentMode { UPI, CARD, NET_BANKING, WALLET}
public class CompleteSwitchDemo { static int fee(PaymentMode m, int amount) { return switch (m) { case UPI -> 0; case CARD -> amount * 2 / 100; case NET_BANKING -> 10; case WALLET -> 5; }; }
public static void main(String[] args) { for (PaymentMode m : PaymentMode.values()) { System.out.println(m + ": Rs. " + fee(m, 1000)); } }}UPI: Rs. 0 CARD: Rs. 20 NET_BANKING: Rs. 10 WALLET: Rs. 5
What this code does
- Every constant has its own case, even the free
UPI, and there is nodefault. - If
EMIis added next year, this method stops compiling untilEMIgets a fee.
The fix is to list every constant, even the ones that share a result, and to leave out default. A plain switch statement is not checked this way, so for decisions that return a value, prefer a switch expression.
Predict the output
What does this switch print?
Read the code and pick what it prints.
Round 1 of 3
WALLET was added later and should cost Rs. 5.
Switching on a null enum
An order loaded from an old record has no status, so its enum field is null. Switching on it throws NullPointerException, and a default branch does not catch it.
Example 6 · Mistake: switching on a null status
enum OrderStatus { PLACED, SHIPPED, DELIVERED}
public class NullSwitchDemo { public static void main(String[] args) { OrderStatus status = null; System.out.println("Checking order"); switch (status) { case PLACED -> System.out.println("Preparing"); case SHIPPED -> System.out.println("On the way"); default -> System.out.println("Done"); } }}Checking order Exception in thread "main" java.lang.NullPointerException: Cannot invoke "OrderStatus.ordinal()" because "<local1>" is null at NullSwitchDemo.main(NullSwitchDemo.java:9)
What this code does
- The switch crashes on line 9 before any branch runs.
defaulthandles constants without a case, nevernull. - The message mentions
ordinal()because the compiled switch looks up the constant's position, andnullhas none.
Give enum fields a starting value, such as OrderStatus.PLACED, so they are never null. Where null can still arrive, check if (status == null) before the switch.
Next step
Check your understanding
11 quick questions