Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will null always hit default label in switch statement in Java 8?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 a NullPointerException is 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:

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading