String a="a";
String b=null;
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc为什么把b的null当是字符串了?我觉得,应该这样才得到anullc的啊。
String a="a";
String b="null";
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc

解决方案 »

  1.   

    String b=null;
    首先b在栈内存中定义了一个句柄。
    但是b并没有指向任何具体的对象。string相加的时候,他就是null,具体的我也解释不清楚。一直就是这样。
      

  2.   

    在字符串像加的时候 不是字符串的会自动转化成字符串再相加 针对LZ的问题也就是说a.toString()+b.toString()+c.toString()答案就是 anullc不知道这样解释对不对`
      

  3.   

    to happy_sky()
    b.toString()是错误的,b为null是不能有toString()方法的。
    String b=null;
    System.out.println(b);
    输出结果为null
    此时b应该被认为是基本数据类型,可能类似类中字段未赋值。
    望高手出来指点
      

  4.   

    to luyang1016(闭月羞花猫) 
    嘿嘿,我也知道一直都是这样的。也不知道怎么解释好。
    to happy_sky()
    b.toString()是错误的,会抛出NullPointerException()。哎,原来是20分的帖子,没人来啊,我已经加到100分了。希望吸引更加多的人来解释一下。
      

  5.   

    因为String d=a+b+c;被编译器编译成 new StringBuffer().append(a).append(b).append(c).toString();StringBuffer.append(Object obj)对null进行特殊处理,代码如下
        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;
        }
      

  6.   

    因为String d=a+b+c;被编译器编译成 String b = new StringBuffer().append(a).append(b).append(c).toString();StringBuffer.append(Object obj)对null进行特殊处理,代码如下
        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;
        }
      

  7.   

    写错了,是
    因为String d=a+b+c;被编译器编译成 String b = new StringBuilder().append(a).append(b).append(c).toString();StringBuffer.append(Object obj)对null进行特殊处理,代码如下
        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;
        }
      

  8.   

    to blh(股市奋斗几十年,一夜回到解放前: () StringBuilder这个class不是1.5才有的吗?
    那以前那些版本,是怎么加的?
      

  9.   

    受blh(股市奋斗几十年,一夜回到解放前: ()启发
    看看了print方法对String输出的处理。
        public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
        }
    jdk中的源代码才是无敌的。
    受教了。
    谢谢blh
      

  10.   

    StringBuilder这个class不是1.5才有的吗?
    以前是StringBuffer
    效果应该是一样的。
      

  11.   

    to yeah920(好无聊啊,天天上班没事做,无聊死了,闷死了,怎么办) (
    就是我开始写的,用StringBuffer :)
      

  12.   

    打印一个对象。就是打印他的toString的结果,而null的toString还是null,所以出现上面的结果