gpt4 book ai didi

java - 对字符串和 null 关键字的 Concat 操作

转载 作者:行者123 更新时间:2023-12-03 23:14:13 24 4
gpt4 key购买 nike

据我了解,当 + 运算符与两个字符串文字一起使用时,会调用 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 characters n, u, l, l).

关于java - 对字符串和 null 关键字的 Concat 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300193/

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