Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8278133

14.11.1: Missing condition to exclude null value as a valid case constant

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • 18
    • 14, 15, 16, 17
    • specification
    •  

       

    • 14

      The bug description below is inaccurate. A constant variable is a valid constant expression, but to be a constant variable, the variable's declaration must initialize the variable with a constant expression. `final String value = null;` does not, in fact, declare a constant variable, so the simple name `value` is not a constant expression and `case value -> ...` is not legal.

      ----------

      The JLS does not include sufficient conditions in 14.11.1 to exclude the null value as a case constant.

      JLS 14.11.1 states that "...null cannot be used as a case constant". This is enforced by requiring that the case constant is a constant expression, as the null literal is not a valid constant expression.

      Whilst necessary, this is not a sufficient condition. A constant variable is a valid constant expression. So, the specification as it stands would permit the following:

      String selector = "hello";
      final String value = null;
      switch (selector){
          case value -> System.out.println("oops");
      }
       
      [Note that the compiler correctly rejects this example.]

      Before the refactoring of the JLS to handle switch expressions, there was the following additional check, which is missing in the current version:

          No case constant associated with the switch statement is null.

      Suggested change: Replace

          Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.

      with the following:

          Every case constant must be either a constant expression (§15.29) that is not null or the name of an enum constant (§8.9.1), or a compile-time error occurs.
       

            abuckley Alex Buckley
            gbierman Gavin Bierman
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: