String str=null;
System.out.println((str+="chen"));
输出结果为 nullchen
为什么呢?

解决方案 »

  1.   

    这个是java底层对out.println()对空值输出的一种约定吧,没必要弄太深
      

  2.   

    直接输出str也是null,等下面的解释。
      

  3.   

    null与“”是不同的。一个是空,一个是空字符串。
    如果:
    String str="";
    System.out.println((str+="chen"));
    输出结果就是 chen
      

  4.   

    Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method. 官方API写得很清楚,println实际上调用的是print方法,所以你查看print的说明就是上面说的那样。
      

  5.   

    有什么比看源码更直接呢?    public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
        }
      

  6.   


    (str+="chen")
    (str = str + "chen")那么实际执行的时候,是借助了StringBuilderStringBuilder sb = new StringBuilder();
    sb.append(str); // 那么关键是这里
    sb.append(chen);
    str = sb.toString();
    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.   

    不好意思,这个解释文不对题,没仔细看LZ问题String str=null;
    System.out.println((str+="chen"));等价于
    String str=null;
    System.out.println(new StringBuilder().append(str).append("chen").toString);我们要看的是append方法的源码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.   

    话说龙四有个Blog跟这个事情有些关系,楼主可以看看,深入分析字符串连接最后编译的字节码。http://www.ticmy.com/?p=69
      

  9.   

    同意五楼,JDK的api表述的很清楚,只是我们用的时候不太留意