日期:2014-05-20  浏览次数:20833 次

String“画蛇添足输出”null字符串的原因是什么?
我是一个C++狂热爱好者,最近尝试了使用java做安卓软件的开发,开发的过程中碰到了一个很奇怪的问题! 在使用String类型的“+”运算拼接字符串的时候,出现了把null作为字符串的情况,很纠结,用一贯的逻辑得不到合理的解释。 
  哪位高人知道其中的原理请留下留贴,共像我这样的小白观摩学习。
  例子如下:
Java code

public class sample{
  public static void main(String[] args){
      String s = null;
      s = s + 1;
      System.out.println(s);
  }
}     


Run result : null1

我请教了公司的大牛,大牛给出的解释是, 当字符串进行拼接计算的时候,系统会默认调用toString()方法,所以当String为null的时候,默认调用s.toString() + 1.toString 的结果就是null1.

基于同事的解释,于是我写了第二版代码:
Java code

public class sample{
  public static void main(String[] args){
      String s = null;
      s = s.toString() + 1;
      System.out.println(s);
  }
}     


Run result : 空指针异常.

我做java一个月有余了吧,各种纠结的问题都出现了,还有有C++的功底基本上大致的逻辑搞清楚了也就明白了。但是这个问题确实狠狠的纠结了我一把。 也纠结了我们公司的同事们一把。 感觉有点画蛇添足的感觉。 既然s.toString()都会报异常,那么s + 1 就没有必要输出null1了。 我的感觉是这样的。 期待大神给出合理的解答。期待...

------解决方案--------------------
了解的这么细,又有什么意义呢?只能是增加了点冷知识而已啊。不如买本书去看好了。

+ 运算是个被重载的运算,其本身用的是StringBuilder。

s = s + 1;

翻译后是:
StringBuilder sb = new StringBuilder();
sb.append(s);
sb.append(1);
s = sb.toString();


接下来估计你会很好奇append(String )是啥效果,如下:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; // 这大概就是你最想看到的了
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}