gpt4 book ai didi

java - `null` 被当作字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:37 25 4
gpt4 key购买 nike

String s = null;
s = s + "hai";
System.out.println(s);

输出:

nullhai

我以为这会让我产生 NPE。

背后的基本逻辑是什么

  • 在使用 +(串联)时不抛出 NPE
  • 在使用 时抛出 NPE。

最佳答案

对于 ,s = s + "hai";在内部,将调用 String.valueOf(null)。该方法会将 null 转换为 "null"

字节码:

public static void main(java.lang.String[])   throws java.lang.Exception;
0: aconst_null
//some code
10: invokestatic #27; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;// check this line
// some other code
27: return

关于java - `null` 被当作字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25720982/

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