jvm常量池

jvm规范中,每个类型都有自己的常量池。常量池是某类型所用常量的一个有序集合,包括直接常量(基本类型,String)和对其他类型、字段、方法的符号引用。之所以是符号引用而不是像c语言那样,编译时直接指定其他类型,是因为java是动态绑定的,只有在运行时根据某些规则才能确定具体依赖的类型实例,这正是java实现多态的基础。

为了对常量池有更具体的认识,下面引用几个例子:

1,常量池中对象和堆中的对象

public class Test{

Integer i1=new Integer(1);
   Integer i2=new Integer(1);
//i1,i2分别位于堆中不同的内存空间

   System.out.println(i1==i2);//输出false


   Integer i3=1;
   Integer i4=1;
//i3,i4指向常量池中同一个内存空间

   System.out.println(i3==i4);//输出true

//很显然,i1,i3位于不同的内存空间

System.out.println(i1==i3);//输出false

}

2,8种基本类型的包装类和对象池

java中基本类型的包装类的大部分都实现了常量池技术,这些类是Byte,Short,Integer,Long,Character,Boolean,另外两种浮点数类型的包装类则没有实现。另外Byte,Short,Integer,Long,Character这5种整型的包装类也只是在对应值小于等于127时才可使用对象池,也即对象不负责创建和管理大于127的这些类的对象。以下是一些对应的测试代码:

public class Test{

public static void main(String[] args){

   //5种整形的包装类Byte,Short,Integer,Long,Character的对象,

   //在值小于127时可以使用常量池

   Integer i1=127;

   Integer i2=127;

   System.out.println(i1==i2)//输出true

   //值大于127时,不会从常量池中取对象

   Integer i3=128;

   Integer i4=128;

   System.out.println(i3==i4)//输出false

   //Boolean类也实现了常量池技术

   Boolean bool1=true;

   Boolean bool2=true;

   System.out.println(bool1==bool2);//输出true

   //浮点类型的包装类没有实现常量池技术

   Double d1=1.0;

   Double d2=1.0;

   System.out.println(d1==d2)//输出false

  

}

}

3,String也实现了常量池技术

String类也是java中用得多的类,同样为了创建String对象的方便,也实现了常量池的技术,测试代码如下:

public class Test{

public static void main(String[] args){

//s1,s2分别位于堆中不同空间

String s1=new String("hello");

String s2=new String("hello");

System.out.println(s1==s2)//输出false

//s3,s4位于池中同一空间

String s3="hello";

String s4="hello";

System.out.println(s3==s4);//输出true

}

}

4.字符串比较更丰富的一个例子

package testPackage;

class Test {

 public static void main(String[] args) {

  String hello = "Hello", lo = "lo";

  System.out.print((hello == "Hello") + " ");

  System.out.print((Other.hello == hello) + " ");

  System.out.print((other.Other.hello == hello) + " ");

  System.out.print((hello == ("Hel"+"lo")) + " ");

  System.out.print((hello == ("Hel"+lo)) + " ");

  System.out.println(hello == ("Hel"+lo).intern());

 }

}

class Other { static String hello = "Hello"; }

and the compilation unit:

package other;

public class Other { static String hello = "Hello"; }

produces the output:

true true true true false true

输出结果的分别解释如下:

在同包同类下,引用自同一String对象.

在同包不同类下,引用自同一String对象.

在不同包不同类下,依然引用自同一String对象

在编译成.class时能够识别为同一字符串的,自动优化成常量,所以也引用自同一String对象

在运行时创建的字符串具有独立的内存地址,所以不引用自同一String对象

String的intern()方法会查找在常量池中是否存在一份equal相等的字符串,如果有则返回一个引用,没有则添加自己的字符串进进入常量池,

注意,只是字符串部分,

所以这时会存在2份拷贝,常量池的部分被String类私有持有并管理,自己的那份按对象生命周期继续使用.

posted on 2011-08-14 12:21  wenfeng762  阅读(7334)  评论(1编辑  收藏  举报