JDK-7029081 : NullPointerException from "cond ? : true : false" type operation
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6u24
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_7
  • CPU: x86
  • Submitted: 2011-03-18
  • Updated: 2025-06-20
  • Resolved: 2011-05-16
Related Reports
Duplicate :  
Description
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.

Comments
EVALUATION The NPE is caused by the unboxing that is required to promote the second expression (a Long in this case) to a numeric type. Not a bug.
16-05-2011