In java Doc it is written that String.valueOf() will return "null" if argument is null, but in practical it gives null pointer exception for null argument. I want to understand the reason. Tried looking on GREPCODE, could not get it. Please explain
Asked
Active
Viewed 1,554 times
-1
-
5See here: http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception – Ulrich Schmidt-Goertz Nov 28 '13 at 11:07
-
2Did you read docs carefully? It says: "Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown." – Simon Dorociak Nov 28 '13 at 11:07
2 Answers
1
If you have code like this:
System.out.println(String.valueOf((Object) null));
"null" is printed to the console. If you have:
System.out.println(String.valueOf(null));
a NPE is thrown.
That is because valueOf is overloaded.
To explain the NPE, if you examine the code for String.valueOf(char[]):
return new String(data);
and the constructor for String is:
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
On this line, a NPE is thrown with the statement value.length.

JamesB
- 7,774
- 2
- 22
- 21