据我了解,当 + 运算符与两个字符串文字一起使用时,会调用 concat 方法来生成预期的字符串。
示例 - String s = "A"+ "B";
当有空值代替下面的一个文字时,它会生成下面的输出。
我在这里很困惑 - 为什么它不抛出 NullPointerException
?
String str = null + "B";
System.out.println(str);
输出:
nullB
最佳答案
why it is not throwing
NullPointerException
.
因为,字符串连接将字符串转换操作应用于非String
类型的操作数,在本例中为null
引用。字符串连接转换为:
String str = new StringBuilder("null").append("B").toString();
不会抛出 NPE
。
来自 JLS §5.1.11 - String Conversion :
This reference value is then converted to type String by string conversion. [...]
- If the reference is
null
, it is converted to the string"null"
(four ASCII charactersn
,u
,l
,l
).
关于java - 对字符串和 null 关键字的 Concat 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300193/