[英]Why does a null value appear in string output?
When I execute the following code the output is "nullHelloWorld".当我执行以下代码时,输出为“nullHelloWorld”。 How does Java treat null?
Java 如何处理空值?
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
.您正在尝试将一个值连接到
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 :这是由“字符串转换”控制的,当一个操作数是
String
时会发生这种情况,并且JLS 第 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).
如果引用为空,则将其转换为字符串“空”(四个 ASCII 字符 n、u、l、l)。
When you try to concat null
through +
operator, it is effectively replaced by a String
containing "null"
.当您尝试通过
+
运算符连接null
,它实际上被包含"null"
的String
替换。
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.这样做的一个好处是,通过这种方式,您可以避免
NullPointerException
,如果您在null
变量上显式调用.toString()
方法,否则您会得到这种.toString()
。
Java treats null as nothing, it is the default value of a String. Java 将 null 视为空,它是 String 的默认值。 It appears in your String output because you use
+=
to add "Hello World" to str
.它出现在您的 String 输出中,因为您使用
+=
将“Hello World”添加到str
。
String str=null;
str+="Hello World";
System.out.println(str);
You are basically telling Java: give my str
variable the type of String
and assign it the value null
;您基本上是在告诉 Java:给我的
str
变量指定String
的类型并将其赋值为null
; now add and assign ( +=
) the String
"Hello World" to the variable str
;现在将
String
“Hello World”添加并分配( +=
)给变量str
; now print out str
现在打印出
str
my two cent:我的两分钱:
String str = null;
str = str.concat("Hello World"); // Exception in thread "main" java.lang.NullPointerException
but但
str += "Hello World";
System.out.println(str); // Hello World
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.