首页 > 系统服务 > 详细

使用eclipse查看堆栈分配

时间:2014-09-03 11:16:26      阅读:304      评论:0      收藏:0      [点我收藏+]

这篇文章源于同事问我说:

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);
	}
}


将每一句打上断点,debug单步运行,可以得到下面的结果:

bubuko.com,布布扣
由此可以得到结论:

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相等。




使用eclipse查看堆栈分配

原文:http://blog.csdn.net/hello_yz/article/details/39024453

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!