Does this function call itself or call the overload?

Consider two overloads:

public void add(Integer value)
    add(value == null ? null : value.doubleValue());        


public void add(Double value)
    // some code here

If I call the first one with a null instance of an Integer, then does the ternary conditional call the overload to a Double, or does it call itself?

On my machine it calls the Double overload, but is this well-defined Java? And what does the JLS say about this?

Jon Skeet

Yes, it's well defined that it will call the Double overload. It couldn't call the Integer overload because there's no implicit conversion from double (which is the type of the conditional expression) to Integer.

Basically, there are two parts of this that are irrelevant:

  • That the method is being called from an overload
  • That the method argument is a conditional expression

So if you think about it as:

Double d = getSomeDoubleValueFromAnywhere();

... which method would you expect to be called? Presumably the add(Double) method - so that's what is called in your situation too.

The tricky part is working out the type of the conditional expression - is it Double or double? I believe the rules (which are hard to follow, IMO) mean that it's Double, due to the use of a null literal (which is of the null type). If instead you had:

Double dv = null;
add(value == null ? dv : value.doubleValue()); 

... then the conditional expression type would be double, and you'd get a NullPointerException if value were ever null, because it would be trying to unbox the null value.


See more on this question at Stackoverflow