当前位置: 代码迷 >> J2SE >> null被挟制转化为字符
  详细解决方案

null被挟制转化为字符

热度:71   发布时间:2016-04-24 00:21:01.0
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……
  相关解决方案