Java - passing null as an argument to print()

10,615

Solution 1

Thank you all for your answers . From your inputs , I compiled the answer myself . It seems the call System.out.print(null) is ambiguous to compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]) . So compiler is unable to determine which method to call here .
Small example will be :

private void methodCall(String str) {
}

private void methodCall(char[] ch){
}

Now this code becomes ambigious : methodCall(null) .

Solution 2

This is because you can pass an Object or a String. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.

Methods definitions:

Instead, if you provide an Object or a String variable (even if it has null value), the compiler would know which method to use.

EDIT: This is better explained in this answer. As to the internal link pointing to the Java specification, you can read it here, and this case would suit here:

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.

It is possible that no method is the most specific, because there are two or more methods that are maximally specific.

Solution 3

It's because System.out.println() expects something with a type. null doesn't have a type, and therefore it can't be output on it's own. This is shown by:

Doesn't work:

 System.out.println(null);

Works:

 System.out.println((String)null);
 System.out.println((char[])null);
 System.out.println((Object)null);

It's the compiler type-checking the parameters of the method call.

Share:
10,615
AllTooSir
Author by

AllTooSir

Updated on June 04, 2022

Comments

  • AllTooSir
    AllTooSir almost 2 years

    I want to know why the below code doesn't work :

    System.out.print(null);    
    response.getWriter().print(null);
    

    But the below ones work :

    String s = null;
    System.out.print(s);
    response.getWriter().print(s);
    

    Whats the difference between passing a null as compared to passing a reference as null ?

    EDITED : Doesn't work fore mentioned indicates to compilation error .