Java中未被初始化的字符串打印出“null”的问题的分析

今天在研究Java面试题的时候发现了这道题,觉得挺有意思,记录下来。 一个为null的字符串被println出来会是什么呢。

public static void main(String[] args) {


String s = null;


System.out.println(s+"aaaa");

}

输出是“nullaaaa” 这是为什么呢,String未被初始化是不可能成为“null”的,因为它是null的。 翻看了一下PrintStream,发现在他打印的时候做了马脚,源码是这样子的

 public void print(String s) {
 if (s == null) {
 s ="null";
}
write(s);
}

还有一个附加的问题是如果打印s+s会发生什么情况,两个null变量相加被打印,首先执行的是相加,查看反编译的Java代码知道是执行了StringBuilder的append方法,我们查看源码

 public AbstractStringBuilder append(String str) {
 if (str == null) str ="null";
 int len = str.length();
 ensureCapacityInternal(count + len);
 str.getChars(0, len, value, count);
 count += len;
 return this;
}

发现一样对null的字符串进行了特殊的处理。

posted @ 2013-05-07 17:56  liubey的自言自语  阅读(340)  评论(0编辑  收藏  举报