读书人

java中的String pool(恒量池)

发布时间: 2012-09-23 10:28:11 作者: rapoo

java中的String pool(常量池)
必须强调一点:java中的String Pool不是在堆区,也不是在栈区(别处看到的)

String a=new String("hello");

先到String pool中看是否存在"hello",因为开始String pool为空,故在String pool中构建对象"hello"。又因为是new操作,故还要以参数"hello"的值拷贝一份在堆内存中构造另一个对象,此时已有两个对象在内存中,a指向堆中的那个"hello"对象。
String a1="hello";

先查看String pool,这是池中有了"hello",故不再在池中构造新的对象了,也不是new操作,堆中也不构造对象,a1指向上步操作中在String pool里构造的那个"hello"对象。
String a2=new String("hello");

String pool中有了"hello",池中不构造新的,但因为有new操作,堆中建立新实例,a2指向这步在堆中构造的那个新"hello"对象

读书人网 >编程

热点推荐