H
Hosam Aly
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.
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.