according to the documentation, the method String.valueOf(Object obj) returns:
if the argument is
null, then a string equal to"null"; otherwise, the value ofobj.toString()is returned.
But how come when I try do this:
System.out.println("String.valueOf(null) = " + String.valueOf(null));
it throws NPE instead? (try it yourself if you don’t believe!)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
How come this is happening? Is the documentation lying to me? Is this a major bug in Java?
The issue is that
String.valueOfmethod is overloaded:String.valueOf(Object)String.valueOf(char[])Java Specification Language mandates that in these kind of cases, the most specific overload is chosen:
JLS 15.12.2.5 Choosing the Most Specific Method
A
char[]is-anObject, but not allObjectis-achar[]. Therefore,char[]is more specific thanObject, and as specified by the Java language, theString.valueOf(char[])overload is chosen in this case.String.valueOf(char[])expects the array to be non-null, and sincenullis given in this case, it then throwsNullPointerException.The easy “fix” is to cast the
nullexplicitly toObjectas follows:Related questions
Moral of the story
There are several important ones:
valueOf(char[])overload is selected!null(examples to follow)See also
On casting
nullThere are at least two situations where explicitly casting
nullto a specific reference type is necessary:nullas a single argument to a vararg parameterA simple example of the latter is the following:
Then, we can have the following:
See also
Related questions