Reputation: 1147
Why String.valueOf(null) is causing null pointer exception? Where the expected behaviour is to return "null" string.
String x = null;
System.out.println(String.valueOf(x));
This give a "null" string. but
System.out.println(String.valueOf(null));
will cause null pointer exception.
Upvotes: 9
Views: 2684
Reputation: 597114
Because String.valueOf(null)
picks the overloaded method with char[]
argument, and then fails in the new String(null)
constructor. This choice is made at compile time.
If you want to explicitly use the overloaded method with a Object
argument, use:
String.valueOf((Object) null)
Note that there is no overloaded method taking a String
argument - the one invoked in the first case is taking Object
.
To quote the JLS:
15.12.2 Compile-Time Step 2: Determine Method Signature
The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments. There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.
All of the methods are applicable, so we go to:
15.12.2.5 Choosing the Most Specific Method
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
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.
Thanks to polygenelubricants - there are only two overloaded methods accepting an object - char[]
and Object
- char[]
is most specific.
Upvotes: 18