9

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.

0

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

8 Comments

null should be considered as a object. why it is considering it as char[]?
@Sujith: Because char[] is an object
@Sujith are you using eclipse, or javac?
There's no misinterpretation. The 2 overloads are valueOf(Object) and valueOf(char[]). There is no such thing as valueOf(String). char[] is more specific than Object. Also, see stackoverflow.com/questions/3131865/…
@polygenelubricants thanks a lot. I've overlooked that fact that there is no String-overloaded method. Thus it all falls into place.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.