Here is a small program that shows a classic statement, a modern expression, and an enum switch with exhaustiveness.
// A modern switch expression over an enum needs no default,
// because the compiler proves every constant is covered.
String badge = switch (status) {
case PENDING -> "GRAY";
case APPROVED -> "GREEN";
case REJECTED -> "RED";
};
That is the form to reach for in real code. It is short, it cannot fall through, and adding a new Status constant breaks the build until you deal with it.
Frequently Asked Questions
What is fall-through and is it ever useful?
Fall-through is when a case without a break continues into the next case body. It is almost always a bug, but it is genuinely useful for grouping several values onto one shared body, which is what stacked case lines achieve.
Should I still learn the classic switch?
Yes, you should recognise it because you will meet it everywhere in older codebases, and it comes up constantly in interviews. Just write the arrow form in new code, since it removes an entire category of bug.
Why can I not switch on a boolean?
By design, not by accident. A boolean has exactly two values, so an if expresses it far more clearly, and a switch would add structure without adding meaning.
Why can I not switch on a long?
It has never been allowed in any version of Java. If you need to branch on a large number, store an int alongside it and switch on that, or use an if chain.
Is default required?
In a classic statement you should always include one. In a modern switch over an enum or a sealed type, the compiler can prove you covered everything, so default becomes optional, and adding one can even be a warning since it may be unreachable.
Can I use a variable as a case value?
No. Case labels must be compile-time constants, literals, enum constants, or in the modern form, patterns. A variable is not known until run time, so it cannot be a case label.
When should I still choose an if ladder instead?
When your conditions are ranges rather than exact values, such as checking whether a number is above a threshold, or when you are combining several different variables. A switch matches one value against exact options, so an if chain is the right tool for range and compound logic.
Does a switch make my program faster?
Not meaningfully. The JVM compiles a switch into a jump table or a lookup, which is efficient, but a well-written if chain over a handful of conditions is already fast enough that you will never measure a difference. Choose a switch for readability and safety, not speed.