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的说明就是上面说的那样。
有什么比看源码更直接呢? public void print(String s) { if (s == null) { s = "null"; } write(s); }
(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; }
不好意思,这个解释文不对题,没仔细看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; }
如果:
String str="";
System.out.println((str+="chen"));
输出结果就是 chen
if (s == null) {
s = "null";
}
write(s);
}
(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;
}
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;
}