Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Should switches over enums include a default branch? Discuss the trade-off between compile-time exhaustiveness and run-time safety for enums that come from other services.

For enums we own, switch expressions should usually have no default branch, because the compiler then checks that every constant is handled and turns a new constant into a build error; a default silences that check and lets new constants fall into the fallback unnoticed. For enums whose values come from other services, the risk is at the parsing boundary, so we map unknown values to an explicit UNKNOWN constant or reject them there, and keep the switches exhaustive. Classic switch statements over enums are not checked at all unless they use patterns or case null, so we prefer switch expressions and add static analysis for the statements that remain.

Why this question is asked

Whether to write a default branch looks like a style question, but it decides when we find out about a new enum constant: at compile time, at run time with an exception, or never, with a silent wrong result. Interviewers ask it to see whether we can weigh compile-time and run-time safety and put each check in the right place. In this answer, we will see what the compiler checks with and without default, what a default really costs, how to handle enums that arrive from other services, and which switches the compiler does not check at all.

1A Quick Recap: What Exhaustiveness Gives Us

A switch is exhaustive when every possible value of its selector is handled. Switch expressions must be exhaustive because they must produce a value. For an enum selector, the compiler accepts the switch either when every constant has a case, or when there is a default branch. In the first case, the compiler also inserts a hidden default that throws MatchException, in case a constant appears at run time that did not exist at compile time.

So without a default, we get two protections: a compile error when the enum gains a constant and the code is recompiled, and an exception rather than a wrong result if old code meets a new constant.

2What a Default Branch Silences

Here are two versions of the same rule for a fee calculation. The enum gains a constant, EXPRESS, and the code is recompiled.

Java
enum Shipping { STANDARD, NEXT_DAY, EXPRESS } // EXPRESS was just added
// Version A: no default
int feeA = switch (shipping) {
case STANDARD -> 0;
case NEXT_DAY -> 9;
}; // compile error: the switch expression does not cover all possible input values
// Version B: with default
int feeB = switch (shipping) {
case STANDARD -> 0;
case NEXT_DAY -> 9;
default -> 0; // compiles; EXPRESS orders now ship for free
};
No default versus default, for an internal enum
EventNo defaultWith default
New constant, code recompiledcompile error at each switchcompiles silently
New constant, old binaryMatchException, loudfalls into default, silent
Behaviour for the new valuedecided by a developerdecided by the old fallback
Good forbusiness rules, state handlingtruly generic fallbacks, such as logging

Version A stops the build and points at the exact line where someone must decide the EXPRESS fee. Version B compiles, passes every existing test, and ships a pricing bug. Nobody chose to make EXPRESS free; the default did, years after it was written, for a constant its author never imagined. That is the core trade-off: a default makes code robust to new constants in the sense that it does not crash, but it does so by guessing, and the guess is usually wrong for business decisions.

3Enums That Arrive From Other Services

The argument for a default usually comes from enums that are not ours: a status from a payment provider, an event type from another team. They can gain values at any time, independent of our releases, and a crash is not acceptable. That concern is real, but the default branch is the wrong place to address it. The problem appears when the external value is turned into our enum, at the parsing boundary, so that is where we handle it.

Java
enum PaymentStatus { AUTHORIZED, CAPTURED, REFUNDED, UNKNOWN }
static PaymentStatus parse(String external) {
try {
return PaymentStatus.valueOf(external);
} catch (IllegalArgumentException e) {
unknownStatus.increment(); // metric: we are behind the provider
log.warn("Unknown payment status {}", external);
return PaymentStatus.UNKNOWN;
}
}
String action = switch (status) { // still exhaustive, no default
case AUTHORIZED -> "capture later";
case CAPTURED -> "ship";
case REFUNDED -> "cancel shipment";
case UNKNOWN -> "hold for manual review"; // an explicit, deliberate decision
};
Step throughWhere to handle a value we do not know
  1. External string arrivesJSON, message, database
  2. Is it a known constant?
    YesMap to that constantNoMap to UNKNOWN or reject, and count it
  3. Exhaustive switch, no defaultUNKNOWN has its own explicit case
  4. Compiler flags our own new constantsat every switch that must handle them

4 steps in order. Play them, or step through them one at a time.

Unknown external values are handled once at the boundary; switches stay exhaustive.

Now the switch is exhaustive and still gets compile-time help when we add a constant of our own, while a new external value becomes UNKNOWN with a visible metric and a deliberate handling decision. With Jackson, the same mapping can be done with a @JsonEnumDefaultValue constant and the read-unknown-enum-values-using-default-value feature. The alternative at the boundary is to reject unknown values with a clear error, which suits API requests that the caller can correct.

4Switches the Compiler Does Not Check

There is a catch. The old switch statement, with case X: and break, or a switch statement with arrows that does not return a value, is not required to be exhaustive when the selector is an enum. Java only requires exhaustiveness for switch statements that use patterns or case null, which were added in Java 21. A plain statement switch that misses a constant compiles without a warning and simply does nothing for it.

Java
switch (shipping) { // statement: not checked for enums
case STANDARD -> scheduleTruck();
case NEXT_DAY -> scheduleCourier();
} // EXPRESS: nothing happens, no error, no warning

So the first rule is to prefer switch expressions whenever the switch makes a decision that must cover every constant. If a statement is clearer, we can make it exhaustive by adding case null -> throw new NullPointerException(), which forces the compiler to check it, though that looks odd to readers. The more common answer is static analysis. Error Prone has a check for missing enum cases in switches, and IntelliJ IDEA and other IDEs flag them; turning such a check into a build error covers the statement switches the language does not.

5When a Default Is the Right Choice

A default is right when the fallback is genuinely correct for any constant that might exist in future, not a guess about business behaviour. Examples are a log message that formats any status, a metrics tag, or a switch over a large external enum where we only care about two values and everything else really means do nothing. In those cases, writing default makes the intent clear. For everything that decides money, state or permissions, we leave default out and let the compiler work for us.

6Follow-up questions

Doesn't the hidden MatchException mean production can crash on a new constant?

Only if old code meets a constant that did not exist when it was compiled, which in practice means an enum shared across deployables or deserialized from outside. Handling unknown values at the parsing boundary and keeping shared enums under a release policy removes that path, while recompiled code is protected at build time.

Can a default branch and exhaustiveness checking coexist?

Not for the same switch: once a default exists, the compiler considers the switch exhaustive and stops checking constants. Some teams write default -> throw new IllegalStateException(), which is loud at run time but still loses the compile-time error, so it is worse than no default.

What about sealed interfaces instead of enums?

The same reasoning applies. A pattern switch over a sealed interface without default is checked against all permitted types, and adding a new record to the hierarchy fails the build at every switch that does not handle it.

7Conclusion

In this answer, we saw that leaving default out of a switch expression over an enum makes the compiler check that every constant is handled, turns a new constant into a build error and makes old code fail loudly with MatchException, while a default branch silently routes new constants into a fallback that was never designed for them. For enums from other services, we handle unknown values once, at the parsing boundary, with an explicit UNKNOWN constant or a rejection, and keep switches exhaustive. Because classic statement switches over enums are not checked, we prefer switch expressions and add static analysis such as Error Prone for the rest.

What to say in the interviewAbout 90 seconds aloud

Open with

My default is no default, at least for switch expressions over enums we own. Without one, the compiler checks that every constant has a case, so when someone adds a constant and recompiles, the build fails at exactly the switches that need a decision, and if old bytecode meets the new constant it throws MatchException rather than guessing.

Then, if they want more

A default silences all of that. For example, if a shipping fee switch has default zero and someone adds EXPRESS, it compiles, tests pass, and express shipping is free. For enums that come from other services, the real risk is at deserialization, not in the switch.

So I handle it at the boundary: an unknown string maps to an explicit UNKNOWN constant with a log line and a metric, or I reject it with a clear error if the caller can fix it, and then the switch stays exhaustive with its own case for UNKNOWN.

I also keep in mind that classic switch statements over enums are not checked for exhaustiveness at all unless they use patterns or case null, so I prefer switch expressions for decisions and use static analysis like Error Prone's missing-cases check for the statements that remain.

I do write default when the fallback is genuinely right for any future value, like logging.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Should switches over enums include a default branch? Discuss the trade-off between...": https://scrivio-interview-library.netlify.app/java/enums/4e52b4460c/