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).