Java 字符串的细微差别
class Test {
public static void main() {
String s1 = null + null; //shows compile time error
String s1 = null;
String s2 = s1 + null; //runs fine
}
}
任何人都可以解释这种行为的原因吗?
class Test {
public static void main() {
String s1 = null + null; //shows compile time error
String s1 = null;
String s2 = s1 + null; //runs fine
}
}
任何人都可以解释这种行为的原因吗?
此代码:
String s1 = null + null;
尝试对两个 执行加法运算,这是无效的。null
而在这里:
String s1 = null;
String s2 = s1 + null;
您分配给 了 。然后执行 和 的串联。的类型是 ,因此 in 将按照字符串转换规则转换为字符串,如 JLS §15.1.11 - 字符串转换中所示:null
s1
s1
null
s1
String
null
s1 + null
"null"
如果引用为 null,则将其转换为字符串(四个 ASCII 字符)。
"null"
n, u, l, l
否则,转换就像通过调用没有参数的引用对象的方法一样执行;但是如果调用该方法的结果是 ,则使用字符串。
toString
toString
null
"null"
和串联将按 - 完成s1 + "null";
仅当一个(或两个)操作数的类型为 时,作为串联的运算符才适用。+
String
String
如果运算符的任一操作数的类型是 ,则该操作是字符串串联。
+
String
在
String s1 = null + null; //shows compile time error
操作数具有类型,即。不是 ,因此不会发生字符串串联。然后Java认为你正在做一个加法,这也不适用于类型。null
String
null
在
String s2 = s1 + null; //runs fine
s2
有类型,即使它是引用的,所以字符串串联可能发生。String
null