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/