When I execute the following code the output is "nullHelloWorld". How does Java treat null?
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String str=null;
str+="Hello World";
System.out.println(str);
}
}
You are attempting to concatenate a value to null
. This is governed by "String Conversion", which occurs when one operand is a String
, and that is covered by the JLS, Section 5.1.11:
Now only reference values need to be considered:
- If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
When you try to concat null
through +
operator, it is effectively replaced by a String
containing "null"
.
A nice thing about this is, that this way you can avoid the NullPointerException
, that you would otherwise get, if you explicitly called .toString()
method on a null
variable.
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