MissingNullCaseInSwitch

Since Checkstyle 10.18.0

Description

Checks that a given switch statement or expression that use a reference type in its selector expression has a null case label.

Rationale: switch statements and expressions in Java throw a NullPointerException if the selector expression evaluates to null. As of Java 21, it is now possible to integrate a null check within the switch, eliminating the risk of NullPointerException and simplifies the code as there is no need for an external null check before entering the switch.

See the Java Language Specification for more information about switch statements and expressions.

Specifically, this check validates switch statement or expression that use patterns or strings in their case labels.

Due to Checkstyle not being type-aware, this check cannot validate other reference types, such as enums; syntactically, these are no different from other constants.

Attention: this Check should be activated only on source code that is compiled by jdk21 or above.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="MissingNullCaseInSwitch"/>
  </module>
</module>
        

Example of violation:

public class Example1 {

  void testString(String obj) {
    // violation below, 'Switch using reference types should have a null case.'
    switch (obj) {
      case "something" : {}
    }
    switch (obj) {
      case null : {}
      case "something" : {}
      default: {}
    }
  }

  void testPatterns(Object obj) {
    // violation below, 'Switch using reference types should have a null case.'
    switch (obj) {
      case Integer i : {} break;
      default : {}
    }
  }

  void testPrimitives(int i) {
    switch (i) {   // ok, this is a primitive type can't be null
      case 1 : {}
    }
  }

  // This example is ok, because Checkstyle is not type-aware. The
  // value of 't' could be an enum constant, a primitive, or a reference type.
  void testEnum() {
    var t = TimeUnit.DAYS;
    switch (t) {
      case SECONDS -> {}
    }
  }

  // This is example is also ok, because we do not know the type
  // of the variable t. It could be an 'int' or an 'Integer'.
  void test() {
    var t = List.of().size();
    switch (t) {
      case 1 : {}
    }
  }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker