gpt4 book ai didi

Java 字符串的细微差别

转载 作者:IT老高 更新时间:2023-10-28 20:25:33 24 4
gpt4 key购买 nike

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;

您将 null 分配给 s1。然后执行 s1null 的串联。 s1的类型是String,所以s1 + null中的null会被转换成"null " 字符串按照字符串转换规则,如JLS §15.1.11 - String Conversion:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

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";

关于Java 字符串的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22969348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com