JDK-6211553 : Unboxing in conditional operator might cause null pointer exception
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P5
  • Status: Closed
  • Resolution: Not an Issue
  • OS: linux,windows_xp
  • CPU: x86
  • Submitted: 2004-12-22
  • Updated: 2010-08-06
  • Resolved: 2006-10-03
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
"1.5.0" build 1.5.0-b64

ADDITIONAL OS VERSION INFORMATION :
WindowsXP sp2

A DESCRIPTION OF THE PROBLEM :
Auto-boxing in ternary operator compiles fine but has an execution failure of NullPointerException when it should execute properly.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Run the code supplied.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
No exception
ACTUAL -
An exception

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

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
class Test {
    public static void main(String[] args) {

        // Java bug!

        String a = null;

        Integer j = 8;
        Integer k = null;

        Integer i = (a != null)
                    ? 5  // okay with j, non-null, but fails on k below when this has Auto-boxing
                    : k;
    }
}

---------- END SOURCE ----------
###@###.### 2004-12-22 01:42:41 GMT
###@###.### 2005-1-03 19:57:36 GMT

Comments
EVALUATION This is not a bug. See JLS3 15.25 (Conditional Operator ? :) http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25 The type of "(a != null) ? 5 : k" is determined based only on the types of 5 and k. This is very deliberate since it makes the typesystem compositional. If it wasn't, then consider what would happen in this scenario: class Test { static void m(int i) { System.out.println("HEST"); } static void m(Integer i) { System.out.println("FISK"); } public static void main(String... args) { Integer k = 4; m(args != null ? 5 : k); } } If the type of the conditonal operator depended on where it is used, it wouldn't be possible to resolve the overloading. However, since the type system is compositional, we know that the type of the argument to m is int so the first method is called and the program prints HEST.
03-10-2006

EVALUATION I need to double check the specification, but this appears to be the specified and expected behavior. ###@###.### 2005-1-05 02:00:32 GMT
05-01-2005