`null` 被视为字符串? [英] `null` is treated as String?
本文介绍了`null` 被视为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String s = null;
s = s + "hai";
System.out.println(s);
输出:
nullhai
认为这会让我 NPE.
Thought this would throw me NPE.
背后的基本逻辑是什么
- 在使用
+
(连接)时不抛出 NPE - 在使用
时抛出 NPE.
- not throwing NPE while using
+
(concatenation) - throwing NPE while using
.
推荐答案
For , s = s + "hai";
在内部,将调用 String.valueOf(null)
.该方法会将 null
转换为 "null"
.
For , s = s + "hai";
Internally, String.valueOf(null)
will be called. That method will convert null
to "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
这篇关于`null` 被视为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文