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.
What you will learn
- Switch on an enum with simple constant names as case labels
- Write exhaustive switch expressions over an enum without default
- Explain how a default branch hides new constants
- Avoid the NullPointerException from switching on a null enum
Topics in this lesson
- case labels use the constant's simple name
- A switch expression must cover every constant
- A default branch hides new constants
- Switching on a null enum
Key points
- In
switch (mode), each label is the simple constant name:case UPI, notcase PaymentMode.UPI. - A switch expression that lists every constant needs no
default, and javac flags any constant that is missing. - A
defaultbranch silently handles constants added later; leave it out of enum switches. - Switching on a
nullenum throwsNullPointerException, even with adefault.
Interview questions this lesson answers
- Why are the case labels in an enum switch written without the enum name?
- Do you need a
defaultin a switch expression over an enum? - What is risky about a
defaultbranch when switching on an enum? - What happens if the enum variable in a switch is
null? - Must a switch statement on an enum cover every constant?
- You add a constant to an enum used all over a large project. How do you find every place that must handle it?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.