Take a look at the following example:
class nul { public static void main (String[] args) { System.out.println (String.valueOf((Object)null)); System.out.println (String.valueOf(null)); } }
The first println
writes null
but the second throws a NullPointerException
.
Why is only the second line worth an exception? And what is the difference between the two null
s? Is there a real null
and a fake null
in Java?
The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.
A null object refers to an object without any reference or an object defined with neutral/null functionality/behavior. These null objects need to be checked to ensure that they are not null while accessing any member or invoking any methods.
@arvin_codeHunk, null is an empty object, whereas "null" is an actual string containing the characters 'n', 'u', 'l', and 'l'. The String here is written as null telling you that you just took the String value of null which is equal to "null" . So a null will not be equal to "null" literal. @arvin_codeHunk..
out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
The first invocation will call the String.valueOf(Object)
method, as you have explicitly typecasted null
to Object
reference. Conversely, the second one will invoke the overloaded String.valueOf(char[])
method, as char[]
is more specific than Object
for a null
argument.
There are other overloaded versions of this method that accept primitive parameters, but those are not a valid match for a null
argument.
From JLS §15.12.2:
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.
A method is applicable if it is either applicable by subtyping (§15.12.2.2), applicable by method invocation conversion (§15.12.2.3), or it is an applicable variable arity method (§15.12.2.4).
[...]
If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen, as specified in section §15.12.2.5.
Now check the source code of both the methods:
// This won't throw NPE for `obj == null` public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } // This will throw `NPE` for `data == null` public static String valueOf(char data[]) { return new String(data); }
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