JDK-6977221 : Ternary operator bug related to autoboxing
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_7
  • CPU: x86
  • Submitted: 2010-08-14
  • Updated: 2012-03-20
  • Resolved: 2010-12-02
Description
FULL PRODUCT VERSION :
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Client VM (build 16.3-b01, mixed mode, sharing)

ADDITIONAL OS VERSION INFORMATION :
Windows 7 32-bit

A DESCRIPTION OF THE PROBLEM :
unexpected NullPointerException after running
	
public static void main(String[] args) {
    Double a = null;
    Double b = null;
    Double c = null == a ? b : 0d;
}

Double c = null == a ? null : 0d;
will work

decompiled code
first piece
    public static void main(String args[])
    {
        Double a = null;
        Double b = null;
        Double c = Double.valueOf(a != null ? 0.0D : b.doubleValue());
    }
crystal clear, why it throws a NPE

second piece... Double c = null == a ? null : 0d;  version
    public static void main(String args[])
    {
        Double a = null;
        Double b = null;
        Double c = a != null ? Double.valueOf(0.0D) : null;
    }

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
run the main method in the Description


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
c equals null
ACTUAL -
NullPointerException on line
Double c = null == a ? b : 0d;

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.NullPointerException

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public static void main(String[] args) {
    Double a = null;
    Double b = null;
    Double c = null == a ? b : 0d;
}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
instead of
	public static void main(String[] args) {
		  Double a = null;
		  Double b = null;
		  Double c = null == a ? b : 0d;
	}
use
                  Double c = null == a ? null : 0d;

not much of a workaround, for often a variable is required (variable b) instead of a particular value (null)

Comments
EVALUATION This is not a bug. The NPE follows from JLS 3rd - 15.25 The type of a conditional expression is determined as follows: [...] Otherwise, binary numeric promotion (��5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. where - 5.6.2 Binary Numeric Promotion If any of the operands is of a reference type, unboxing conversion (��5.1.8) is performed. Then: If either operand is of type double, the other is converted to double.[...] This means that the first operand needs to undergo an unboxing conversion - which leads to the NPE (because the compiler will perform that by calling valueOf on the 'null' reference).
02-12-2010