JDK-7074459 : Java compiler allow to return null in a method signature that returns int
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 6u26
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_7
  • CPU: x86
  • Submitted: 2011-08-03
  • Updated: 2025-06-20
  • Resolved: 2011-08-03
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 6.1.7601]

A DESCRIPTION OF THE PROBLEM :
The following code should not compile, however it does compile and throws NullPointerException

public int foo()
{
   return 1==1 ? null : 1;
}

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
See description

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
This code should not compile. I should not be able to return null if the method signature expects int
ACTUAL -
Code was compiled without any warning or error.At runtime this code produces NullPonterException

REPRODUCIBILITY :
This bug can be reproduced always.

Comments
EVALUATION This behavior is expected. Note that javac is not allowing to return 'null' from a method whose expected return type is 'int'. Rather, javac sees that the type of the conditional operator is Integer, which is compatible with 'int'. The reason as to why the conditional operator is typed 'Integer' can be found in the JLS, section 15.25 - here are the relevant bits: "Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7)." Here we have that S1 = <nulltype>, S2 = int So, T1 = <nulltype>, T2 = Integer. T = lub(<nulltype>, Integer) = Integer. This means that each operand of the ternary operator must be converted to Integer - which implies that both operand undergo a boxing conversion. Since the first operand is 'null', the first boxing conversion issues an NPE.
03-08-2011