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

Switch case label "null" cannot be combined with an other label anymore

XMLWordPrintable

    • 20
    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      openjdk version "20.0.2" 2023-07-18
      OpenJDK Runtime Environment (build 20.0.2+9-78)
      OpenJDK 64-Bit Server VM (build 20.0.2+9-78, mixed mode, sharing)

      Run on Mac OS 13.4.1

      A DESCRIPTION OF THE PROBLEM :
      The jep 433 introduced the null case label. In previous versions (< java 20), the null case could be combined with other cases. Like this
      switch (o) {
        case null, Integer i -> {}
        default -> {}
      }
      Now the compiler outputs an error: invalid case label combination

      REGRESSION : Last worked in version 19

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Here's a minimal code sample. Run it with
      java --enable-preview --source=20 Test.java

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The code is expected to compile
      ACTUAL -
      Test.java:6: error: invalid case label combination
                  case null, A -> System.out.println("null or A");
                             ^
      Note: Test.java uses preview features of Java SE 20.
      Note: Recompile with -Xlint:preview for details.
      1 error
      error: compilation failed

      ---------- BEGIN SOURCE ----------
      public class Test {
          public static void main(String[] args) {
              enum E {A, B}
              E e = E.A;
              switch (e) {
                  case null, A -> System.out.println("null or A");
                  case B -> System.out.println("B");
              }
          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      The null case is actually combinable with the default clause. So this works

      public class Test {
          public static void main(String[] args) {
              enum E {A, B}
              E e = E.A;
              switch (e) {
                  case B -> System.out.println("B");
                  case null, default -> System.out.println("null or A");
              }
          }
      }

      FREQUENCY : always


            jlahoda Jan Lahoda
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: