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

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

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 17, 22, 23
    • 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


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

              Created:
              Updated:
              Resolved: