Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - passing null as an argument to print()

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 .

like image 612
AllTooSir Avatar asked Jun 16 '26 10:06

AllTooSir


1 Answers

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:

  • System.out.print(Object)
  • System.out.print(String)

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.

like image 51
Luiggi Mendoza Avatar answered Jun 17 '26 23:06

Luiggi Mendoza