这篇文章源于同事问我说:
String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
str1 == str2为true,是不是表示str1和str2分配在栈上面的?他们没有被new空间。
然后LZ自己YY了一下,想了个办法用eclipse来查看变量的堆栈分配,权威性有待考证,如有不当,有劳赐教!
测试程序如下:
public class StackStringTest {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str3 == str4);
int a = 1;
Integer b = new Integer(1);
System.out.println(a);
System.out.println(b);
}
}
由此可以得到结论:
1.不管是String a ="a",还是String a = new String("a"),他们都是分配在对堆上面的(都有id,而int 类型的a没有id)
2.之所以str1 == str2为true,是因为执行str2 = "abc"这条语句时,系统先检测了存在value为“abc”的这个地址空间(id=19),为了节省空间,也就不再为str2重新new一块区域,而是直接指向str1所在堆区间,所以str1和str2的id相等。