Java Strings微妙的差异 [英] Java Strings subtle differences
问题描述
class Test {
public static void main() {
String s1 = null + null; //shows compile time error
String s1 = null;
String s2 = s1 + null; //runs fine
}
}
任何人都可以解释原因这种行为?
Can anybody please explain the reason for this behavior?
推荐答案
此代码:
String s1 = null + null;
尝试对两个 null
执行加法运算,这是无效的。
tries to perform addition operation on two null
, which is not valid.
在这里:
String s1 = null;
String s2 = s1 + null;
您已将 null
分配给 S1
。然后执行 s1
和 null
的连接。 s1
的类型是 String
,所以 null
in s1 + null
将根据字符串转换规则转换为null
字符串,如 JLS§ 15.1.11 - 字符串转换:
You assigned null
to s1
. Then you perform concatenation of s1
and null
. The type of s1
is String
, so null
in s1 + null
will be converted to "null"
string as per the String conversion rules, as in JLS §15.1.11 - String Conversion:
如果引用为null,则将其转换为字符串
null
(四个
ASCII字符n,u,l,l
)。
否则,执行转换就像执行一样通过调用没有参数的引用对象的
toString
方法;但是如果调用 toString
方法的
结果是 null
,那么字符串null
使用
。
Otherwise, the conversion is performed as if by an invocation of the
toString
method of the referenced object with no arguments; but if the
result of invoking the toString
method is null
, then the string "null"
is used instead.
并且串联将作为 - s1 +null;
and concatenation will be done as - s1 + "null";
这篇关于Java Strings微妙的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!