JDK-8042739 : Ternary operator return NullPointerException instead of return null value
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 7u55
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: os_x
  • CPU: x86
  • Submitted: 2014-05-06
  • Updated: 2025-06-20
  • Resolved: 2014-05-08
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.7.0_55"
Java(TM) SE Runtime Environment (build 1.7.0_55-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Darwin dalloca.local 13.1.0 Darwin Kernel Version 13.1.0: Wed Apr  2 23:52:02 PDT 2014; root:xnu-2422.92.1~2/RELEASE_X86_64 x86_64

A DESCRIPTION OF THE PROBLEM :
Running the code below raises a java.lang.NullPointerException instead of return the null value:

public class JVMBug {

    private Integer value2 = null;

    public static void main(String args[]) {
        JVMBug jvmBug = new JVMBug();
        jvmBug.testValue();
    }

    public Integer testValue() {
        int value = 0;
        return value > 0 ? value : value2;
    }
}

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Just run the sample code.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Run the code without any errors.
ACTUAL -
JVM raises a java.lang.NullPointerException.

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.NullPointerException
	at JVMBug.testValue(JVMBug.java:12)
	at JVMBug.main(JVMBug.java:7)


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public class JVMBug {

    private Integer value2 = null;

    public static void main(String args[]) {
        JVMBug jvmBug = new JVMBug();
        jvmBug.testValue();
    }

    public Integer testValue() {
        int value = 0;
        return value > 0 ? value : value2;
    }
}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Changing the primitive type o Integer in 2nd line solve the issue (or change the ternary to if-else clause).



Comments
This seems to be in accordance with JLS: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25 "If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (ยง5.1.7) to T, then the type of the conditional expression is T." Result of Ternary operator is int, thus value2 gets unreferenced. That's where NPE happens.
08-05-2014