Is null value guaranteed to hit default label in switch statement in case the checked value is null, for Java 8? I guess it should be also the case for any Java version prior to Java 18, where null matching was introduced.
Integer i = null;
switch (i) {
case 1:
// ...
break;
default:
System.out.println("default hit");
}
Oracle docs says
The
defaultsection handles all values that are not explicitly handled by one of thecasesections.
Will default always handle null correctly? Is there a possibility of NullPointerException?
>Solution :
The relevant section of the JLS says this:
A switch statement is executed by first evaluating the selector expression. Then:
- […]
- Otherwise, if the result of evaluating the selector expression is
null, then aNullPointerExceptionis thrown and the entire switch statement completes abruptly for that reason.
So no, a null value will never cause the default case (or any other case) to be executed.
Earlier, in a non-normative section the spec explains:
nullcannot be used as acaseconstant because it is not a constant expression. Even ifcase nullwas allowed, it would be undesirable because the code in that case would never be executed. This is due to the fact that, given a selector expression of a reference type (that is,Stringor a boxed primitive type or an enum type), an exception will occur if the selector expression evaluates tonullat run time. In the judgment of the designers of the Java programming language, propagating the exception is a better outcome than either having no case label match, or having thedefaultlabel match.