日期:2014-05-20 浏览次数:20946 次
public class NullTest {
public static void main(String[] args) {
String str1=null;
String str2=null;
String str3=str1+str2;
System.out.println(str3);//问题1,别运行,打印什么?
//问题2,str3存储在哪?
//问题3System.out.println(str3==?);这里的?写什么才会打印true
}
}
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
------解决方案--------------------
1
String对象相加,内部会使用StringBuilder来操作,就像10L说的
所以 str1+str2 会变成 StringBuilder.apennd("null").append("null")
2
str3保存在堆中
3
从1可以知道,str3是由StringBuilder对象的toString方法在堆中生成的对象,除了str3外没有其他引用变量引用该对象,所以只能自己==自己,才能返回 true