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; }
------解决方案--------------------