Hello,
I was playing with some code today, and then I hard-coded the line:
System.out.println(String.valueOf(null));
At first, I expected this line to call the overload
"String.valueOf(Object)", printing "null" to the output stream.
However, I noticed that it called the "String.valueOf(char[])"
overload, throwing a NullPointerException.
Although my first expectation is incorrect, I am thinking about why
the char[] overload was called automatically, and why the compiler
didn't complain about this being an ambigious call, in the same way it
would do had there been another overload like
"String.valueOf(Integer)".
I guess this either has to do with the Java Language Specification, or
a decision made for the compiler. Could you please explain to me why
the compiler takes this behavior? In my opinion, it would have been
safer to complain about it. Am I wrong? Why?
Thanks a lot for your help.
Roedy Green - 27 Oct 2007 13:08 GMT
>At first, I expected this line to call the overload
>"String.valueOf(Object)", printing "null" to the output stream.
>However, I noticed that it called the "String.valueOf(char[])"
>overload, throwing a NullPointerException.
According to http://java.sys-con.com/read/34292_2.htm
that is a bug. It should complain of ambiguity.
There are Delphic Oracles who can divine meaning in the incantations
of the JLS. We must await their definitive answer.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Patricia Shanahan - 27 Oct 2007 14:10 GMT
> Hello,
>
[quoted text clipped - 16 lines]
> the compiler takes this behavior? In my opinion, it would have been
> safer to complain about it. Am I wrong? Why?
See
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#18428
The accessible, applicable methods for the call are valueOf(Object) and
valueOf(char []). The other valueOf methods in String either require
more arguments, or have a primitive argument type.
char[] is a subclass of Object, so the char[] method is unambiguously
more specific than the valueOf(Object) method.
This is an artificial case, because the explicit "null" makes the type
of the expression the null type, which is can be converted by widening
reference conversion to any reference type. That convertibility is why
you can write:
char[] x = null;
with no explicit cast.
Normally, you would have a null expression of some other type, such as a
null String reference. In that case, the char[] version would not be
applicable unless the type of the expression were char[].
Patricia