-1

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

Nikhil
  • 1
  • 1
  • 5
    See here: http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception – Ulrich Schmidt-Goertz Nov 28 '13 at 11:07
  • 2
    Did 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 Answers2

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.

String.valueOf(Object)

String.valueOf(char[])

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
0

Your call activates String.valueOf(char value[]) that throws NPE in case of null argument. String.valueOf(Object value) works only if you drop the object to this method. Have a look at here

Community
  • 1
  • 1
Maksim
  • 449
  • 4
  • 11