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

标签 java string nullpointerexception

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/

相关文章:

java - 如何调整Java Swing布局中的组件?

java - 你曾经在任何项目中使用过 PhantomReference 吗?

java - 如何将文本文件的第一句话作为点之前的字符串删除?

android - 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' 上的 RecyclerView + ViewPager NullPointerException

java - csv 文件的内容显示在网页上,而不是正确的文件下载

java - 如何在 Java 中使用 Cucumber DataTable 匹配包含 ("${") 的参数值

java - 将字符串拆分为 3 部分并转换为 int

c# - 如何计算字符串中特定字符的集合

android - findViewById 在 <include>d View 内的 LinearLayout 上返回 null

java - Android,如何在 Parcelable 类中正确使用 readTypedList 方法?