Oracle docs reads
The
default
section handles all values that are not explicitly handled by one of thecase
sections.
However, when I ran the following code
Integer i = null;
switch (i) {
case 1:
// ...
break;
default:
System.out.println("default hit");
}
, NullPointerException
was thrown. Will null
always cause NullPointerException
to be thrown or is there a possibility that it will hit default
label in switch
statement? I guess it should be also the case for any Java version prior to Java 18, where null
matching was introduced.
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 aNullPointerException
is thrown and the entire switch statement completes abruptly for that reason.
So 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:
null
cannot be used as acase
constant because it is not a constant expression. Even ifcase null
was 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,String
or a boxed primitive type or an enum type), an exception will occur if the selector expression evaluates tonull
at 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 thedefault
label match.