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

null被强制转化为字符?
String str=null;
System.out.println((str+="chen"));
输出结果为 nullchen
为什么呢?

------解决方案--------------------
探讨
String str=null;
System.out.println((str+="chen"));
输出结果为 nullchen
为什么呢?

------解决方案--------------------
不好意思,这个解释文不对题,没仔细看LZ问题

String str=null;
System.out.println((str+="chen"));

等价于
String str=null;
System.out.println(new StringBuilder().append(str).append("chen").toString);

我们要看的是append方法的源码
Java code

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;
    }

------解决方案--------------------
探讨

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 the……