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

Casting null to Long when using a ternary conditional operator

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      JDK: Eclipse Adoptium JDK-21.0.3.9-Hotspot

      A DESCRIPTION OF THE PROBLEM :
      In a ternary conditional construction, if the return value might either be a primitive long or null, the compiler does not throw an error.

      A primitive long and null are incompatible. Hence, it is expected that the behavior of the compiler is similar to how it would behave if the return value might have been "a primitive long or a string". In case of "a primitive long or a string", the compiler throws an error like:
      >>
      java: incompatible types: bad type in conditional expression
          bad type in conditional expression
            java.lang.String cannot be converted to java.lang.Long
      <<

      Example code to reproduce the issue:
      >>
      Object a = null;
      final Long b = a instanceof Long ? Long.class.cast(a).longValue() : a instanceof Integer ? Integer.class.cast(a).longValue() : null;
      <<

      The example throws a
      >>
      java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()"
      <<
      on runtime.



            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: