The negated instanceof pattern in the last else if clause does not take effect

XMLWordPrintable

    • Type: Bug
    • Resolution: Not an Issue
    • Priority: P4
    • None
    • Affects Version/s: 17, 22, 23
    • Component/s: tools
    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      Windows 11 Pro
      java version "22" 2024-03-19
      Java(TM) SE Runtime Environment (build 22+36-2370)
      Java HotSpot(TM) 64-Bit Server VM (build 22+36-2370, mixed mode, sharing)

      A DESCRIPTION OF THE PROBLEM :
      The negated instanceof pattern matching in the last else if clause does not seem to understand the complete branch path. The converted variable cannot be used later.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Methods f1 and f2 are completely equivalent, but behave differently, which seems strange.
      ACTUAL -
      Methods f2 won't compile

      ---------- BEGIN SOURCE ----------
      public class Main {
          void f1(Object obj) {
              if (obj == this) {
                  return;
              }
              if (!(obj instanceof Main other)) {
                  return;
              }
              System.out.println(other);
          }

          void f2(Object obj) {
              if (obj == this) {
                  return;
              } else if (!(obj instanceof Main other)) {
                  return;
              }
              System.out.println(other);
          }
      }

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

      FREQUENCY : always


            Assignee:
            Jan Lahoda
            Reporter:
            Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: