Why does String.valueOf(null) throw a NullPointerException?
The issue is that String.valueOf
method is overloaded:
String.valueOf(Object)
String.valueOf(char[])
Java Specification Language mandates that in these kind of cases, the most specific overload is chosen:
JLS 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-an Object
, but not all Object
is-a char[]
. Therefore, char[]
is more specific than Object
, and as specified by the Java language, the String.valueOf(char[])
overload is chosen in this case.
String.valueOf(char[])
expects the array to be non-null
, and since null
is given in this case, it then throws NullPointerException
.
The easy "fix" is to cast the null
explicitly to Object
as follows:
System.out.println(String.valueOf((Object) null));
// prints "null"
Related questions
- How does polymorph ambiguity distinction work?
- Which overload will get selected for null in Java?
Moral of the story
There are several important ones:
- Effective Java 2nd Edition, Item 41: Use overloading judiciously
- Just because you can overload, doesn't mean you should every time
- They can cause confusion (especially if the methods do wildly different things)
- Using good IDE, you can check which overload is selected at compile time
- With Eclipse, you can mouse-hover on the above expression and see that indeed, the
valueOf(char[])
overload is selected!
- With Eclipse, you can mouse-hover on the above expression and see that indeed, the
- Sometimes you want to explicitly cast
null
(examples to follow)
See also
- Polymorphism vs Overriding vs Overloading
- Method Overloading. Can you overuse it?
On casting null
There are at least two situations where explicitly casting null
to a specific reference type is necessary:
- To select overloading (as given in above example)
- To give
null
as a single argument to a vararg parameter
A simple example of the latter is the following:
static void vararg(Object... os) {
System.out.println(os.length);
}
Then, we can have the following:
vararg(null, null, null); // prints "3"
vararg(null, null); // prints "2"
vararg(null); // throws NullPointerException!
vararg((Object) null); // prints "1"
See also
- Java Language Guide/varargs - to understand how it's implemented
Related questions
- Why null cast?
- Difference between double… and double[] in formal parameter type declaration
Java String.valueOf(null) throws NPE, but Object a = null; String.valueOf(a) returns 'null'
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
avalueOf(String)
method as well asvalueOf(Object)
and
valueOf(char[])
then a call to the untypedString.valueOf(null)
would be ambiguous
Why String.valueOf(null) is causing null pointer exception?
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.
Why null String is returned in String.valueOf instead of java null?
Because String.valueOf()
returns a String
representation, which for a null
is "null"
.
The developer shouldn't be checking the return value at all, since it's meant for display purposes, not for checking whether a reference was null or not.
String.ValueOf() to replace NULL with string null when calling a method
If this.kind
is null, you should be able to determine that from the stacktrace.
You can handle the situation by adding an if-condition or code like
String.valueOf(this.kind == null ? null : this.kind.name()).toLowercase()
Why doesn't equals throw NullPointerException when one of the variables is pointing to null
It's because the contract for the equals
method, as specified in the Javadoc for the Object.equals method , explicitly states:
For any non-null reference value x, x.equals(null) should return false.
If the method threw a NullPointerException, it would be non-compliant with the contract.
Boolean.valueOf() produces NullPointerException sometimes
You've got to look carefully at which overload is being invoked:
Boolean.valueOf(null)
is invokingBoolean.valueOf(String)
. This doesn't throw anNPE
even if supplied with a null parameter.Boolean.valueOf(modifiedItems.get("item1"))
is invokingBoolean.valueOf(boolean)
, becausemodifiedItems
's values are of typeBoolean
, which requires an unboxing conversion. SincemodifiedItems.get("item1")
isnull
, it is the unboxing of that value - not theBoolean.valueOf(...)
- which throws the NPE.
The rules for determining which overload is invoked are pretty hairy, but they roughly go like this:
In a first pass, a method match is searched for without allowing boxing/unboxing (nor variable arity methods).
- Because
null
is an acceptable value for aString
but notboolean
,Boolean.valueOf(null)
is matched toBoolean.valueOf(String)
in this pass; Boolean
isn't an acceptable for eitherBoolean.valueOf(String)
orBoolean.valueOf(boolean)
, so no method is matched in this pass forBoolean.valueOf(modifiedItems.get("item1"))
.
- Because
In a second pass, a method match is searched for, allowing boxing/unboxing (but still not variable arity methods).
- A
Boolean
can be unboxed toboolean
, soBoolean.valueOf(boolean)
is matched forBoolean.valueOf(modifiedItems.get("item1"))
in this pass; but an unboxing conversion has to be inserted by the compiler to invoke it:Boolean.valueOf(modifiedItems.get("item1").booleanValue())
- A
(There's a third pass allowing for variable arity methods, but that's not relevant here, as the first two passes matched these cases)
String says its not null but then later throw NullPointerException
Since you get the string from a servlet i can say that this is normal.
Java converts a null string to a "null" string on some conditions.
Obviously the string you retrieve is not a null value, but it is a 4 char string "null"
Why don't you try debugging? Or just see what does this return:
System.out.println("Length of ID: " + ID.Length);
Edit: If you don't get exception here, this means that the string is not null and also output "Length of ID: 4" will mean that the string is really ID = "null"
EDIT2: Alright it seems that some guys do not understand what is going on here and they say how can a null string be "null" in some conditions in Java? They find it riddiculus. I prefer them to try this on java:
String abc = null;
String xyz = "hello";
System.out.println(xyz + abc);
The output will be "hellonull" Nothing else...
Also here we have a servlet. There is a null data. Servlet sends the null data as "null" what should it do? An empty string? Come on!!! "
Related Topics
Converting an Array of Objects to an Array of Their Primitive Types
How to Create Sparksession with Hive Support (Fails with "Hive Classes Are Not Found")
How to Format a Java String with Leading Zero
How Can a Class Have a Member of Its Own Type, Isn't This Infinite Recursion
How to Sort an Arraylist of Objects by a Property
Docker: Combine Multiple Images
How to Increase Ide Memory Limit in Intellij Idea on MAC
How to Create an Asynchronous Http Request in Java
Retrieving the Inherited Attribute Names/Values Using Java Reflection
Platform Independent Paths in Java
Converting a Java Keystore into Pem Format
Are "While(True)" Loops So Bad
Convert a String (Like Testing123) to Binary in Java
Safe String to Bigdecimal Conversion
What Is "The Inverse Side of the Association" in a Bidirectional JPA Onetomany/Manytoone Association