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

NullPointerException from "cond ? : true : false" type operation

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 6u24
    • core-libs
    • x86
    • windows_7

      FULL PRODUCT VERSION :
      Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
      Java HotSpot(TM) Client VM (build 19.1-b02, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 6.1.7601]

      A DESCRIPTION OF THE PROBLEM :
      Code like this gives NullPointerException if aNullValue argument is null:

      public static Long toTimeValue(final Date aDate, final Long aNullValue) {
      return (aDate == null) ? aNullValue : aDate.getTime();
      }

      Java decompiler shows that javac has changed code to:

      public static Long toTimeValue(Date aDate, Long aNullValue) {
      return Long.valueOf(aDate != null ? aDate.getTime() : aNullValue.longValue());
      }

      Above decompiled code shows that java compiler has done incorrect optimization for original code.

      REGRESSION. Last worked in version 6u24

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      public class Test {
        public static Long toTimeValue(final Date aDate, final Long aNullValue) {
          return (aDate == null) ? aNullValue : aDate.getTime();
        }
        public static void main(String[] args) {
          Long result = toTimeValue(null, null);
          System.out.println("result="+result);
        }
      }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should have printed out:
      result=null
      ACTUAL -
        Program gives NullPointerException.

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      Exception in thread "main" java.lang.NullPointerException
      at Test.toTimeValue(Test.java:18)
      at Test.main(Test.java:21)

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public class Test {
        public static Long toTimeValue(final Date aDate, final Long aNullValue) {
          return (aDate == null) ? aNullValue : aDate.getTime();
        }
        public static void main(String[] args) {
          Long result = toTimeValue(null, null);
          System.out.println("result="+result);
        }
      }

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

      CUSTOMER SUBMITTED WORKAROUND :
      If ternary operator is replaces with normal if:

          if (aDate == null) {
            return aNullValue;
          } else {
            return aDate.getTime();
          }

      Then problem disappears.

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

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: