Is there a logical language-design-type explanation for the following behaviour (Java 7 and I suspect earlier editions as well):
Object a = null; String as = String.valueOf(a); // as is assigned "null" System.out.println(as+":"+as.length()); // prints: "null:4" System.out.println ( String.valueOf(null)); // NPE
The String. valueOf(Object) method, as its Javadoc-generated documentation states, returns "null" if the passed in object is null and returns the results on the passed-in Object 's toString() call if the passed-in Object is not null.
The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
Java - String valueOf() Method valueOf(boolean b) − Returns the string representation of the boolean argument. valueOf(char c) − Returns the string representation of the char argument.
String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
In statement System.out.println(String.valueOf(null));
there is a call of method public static String valueOf(char data[])
, which source code is as follows:
public static String valueOf(char data[]) { return new String(data); }
That is why you get NPE
On the other hand, in statement Object a = null; String as = String.valueOf(a);
there is a calls of method public static String valueOf(Object obj)
, which source code is as follows:
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
That is why you get "null" instead of NPE
A bit of theory from Java Language Specification: 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.
A char[]
is of type Object
, but not all Object
are of type char[]
. Type char[]
is more specific than Object and as described in the Java Language Specification, the String.valueOf(char[])
overload is chosen in this case.
EDIT
It is also worth mentioning what Ian Roberts mentioned (in his comment below):
It's important to note that it's a compile error if there is no single overloading that is more specific than all the others - if there were a
valueOf(String)
method as well asvalueOf(Object)
andvalueOf(char[])
then a call to the untypedString.valueOf(null)
would be ambiguous
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With