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);
}
}
Java treats null as nothing, it is the default value of a String. It appears in your String output because you use
+=
to add "Hello World" tostr
.You are basically telling Java: give my
str
variable the type ofString
and assign it the valuenull
; now add and assign (+=
) theString
"Hello World" to the variablestr
; now print outstr
When you try to concat
null
through+
operator, it is effectively replaced by aString
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 anull
variable.You are attempting to concatenate a value to
null
. This is governed by "String Conversion", which occurs when one operand is aString
, and that is covered by the JLS, Section 5.1.11: