How does overload resolution work with a null argument?

Why is the method with a parameter of type Object[] called rather than the method with a parameter of type Object when null is passed as the argument?

class Demo {
    void show(Object arr[]) {
        System.out.println("khawar");
    }

    public void show(Object o) {
        System.out.println("aleem");
    }

    public static void main(String[] args) {
        Demo ss=new Demo();
        ss.show(null);
    }
}
Jon Skeet
people
quotationmark

Firstly, it's important to note that the null value is convertible to both Object and Object[], so both methods are applicable. Then it's just a matter of overload resolution. That's described in section 15.12 of the JLS, and section 15.12.2.5 in particular talks about finding "the most specific method", which includes:

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

That's the case here: any invocation of show(Object[]) can be passed to show(Object) without a compile-time type error, therefore show(Object[]) is more specific than show(Object), so overload resolution picks show(Object[]) to invoke.

To invoke show(Object) you just have to cast the null to Object, to stop the show(Object[]) method from being applicable:

ss.show((Object) null);

people

See more on this question at Stackoverflow