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

Compiler wrongly add an invokevirtual of *numeric*Value

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      OS: Microsoft Windows 11 Business / 10.0.26100 build 26100
      Java runtime:
      openjdk version "21.0.7" 2025-04-15 LTS
      OpenJDK Runtime Environment Microsoft-11369940 (build 21.0.7+6-LTS)
      OpenJDK 64-Bit Server VM Microsoft-11369940 (build 21.0.7+6-LTS, mixed mode, sharing)

      A DESCRIPTION OF THE PROBLEM :
      Writing a method that safetly sums two Numerics (namely Double, Float, Integer and Long), using a ternary operator to return null in case of sum of two nulls, behaves unexpectedly, generating an NPE.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run and compile the given source code
      javac SumUtils.java
      java SumUtils

      EXPECTED VS ACTUAL BEHAVIOR
      EXPECTED -
      null
      ACTUAL -
      Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Double.doubleValue()" because "<parameter2>" is null
              at SumUtils.safeSum(SumUtils.java:9)
              at SumUtils.main(SumUtils.java:5)

      ---------- BEGIN SOURCE ----------
      public class SumUtils {
        private SumUtils() {}
        
        public static void main(String... args) {
          System.out.println(safeSum(null, null));
        }

        static Double safeSum(Double a, Double b) {
          return a == null ? b
               : b == null ? a
               : a + b;
        }
      }
      ---------- END SOURCE ----------

            pmtavare Patricia Tavares
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: