Search code examples
java-8nullpointerexceptionnullswitch-statement

Will null always cause NullPointerException in switch statement in Java 8?


Oracle docs reads

The default section handles all values that are not explicitly handled by one of the case 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.


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 a NullPointerException 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 a case constant because it is not a constant expression. Even if case 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 to null 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 the default label match.