I am using the code:
System.out.println(null);
It is showing the error:
The method println(char[]) is ambiguous for the type PrintStream
Why doesn't null
represent Object
?
I am using the code:
System.out.println(null);
It is showing the error:
The method println(char[]) is ambiguous for the type PrintStream
Why doesn't null
represent Object
?
There are 3
println
methods inPrintStream
that accept a reference type -println(char x[])
,println(String x)
,println(Object x)
.When you pass
null
, all 3 are applicable. The method overloading rules prefer the method with the most specific argument types, soprintln(Object x)
is not chosen.Then the compiler can't choose between the first two -
println(char x[])
&println(String x)
- sinceString
is not more specific thanchar[]
and vice versa.If you want a specific method to be chosen, cast the null to the required type.
For example :
If you call
System.println(null)
there are multiple candidate methods (withchar []
,String
andObject
argument) and the compiler can't decide which one to take.Fix
Add an explicit cast to null.
Or use null object pattern.
From JLS 4.1 The Kinds of Types and Values
So the type of
null
is notObject
, though it can be converted to (read-as assigned to) anObject
.