java字符串池_Java字符串常量池

字符串

字符串字面量:就是指这个字符串本身,比如"Java","Hello"。

字符串对象:比如new String("abc"),或者直接String s="str",后面的"str"也是一个字符串对象。

字符串引用:引用就是一个变量,指向对应的字符串对象。

常量池

class常量池

Java源文件编译之后得到的class文件,其中有项信息就是常量池,保存有字面量和符号引用,比如

public class JvmClass1 {

final int b=666;

public static void main(String[] args) {

String c="java";

String d="abcd";

}

}

对应的class文件中

dc2858f39c137b17f076a7fa0df034fc.png

dd69ab841d978416a436c45827b155ae.png

这一项就是666这个字面量。

181dea0387ea4cbe5541eef35ed348db.png

55167921b697a4ad85e59e430188ecc4.png

这两项就是java和abcd这两个字符串的字面量。

而符号引用也是一些常量,比如全限定类名,字段的名称和描述符,方法的名称和描述符。

9879068a565548b385fb65df0584e44f.png

bd4a449aa864bbb06da61c5f2f6fe741.png

这是类名。

1baa1aad8d6d973768061ac09c2d01b5.png

8800622ebac305bc6218bde9e759fb6d.png

这是变量名。

常量池中有一些常量类型有index属性,指向另外一个字面量,比如CONSTANT_Class_Info,CONSTANT_String_Info等。

相同的字符串字面量在常量池中只会保存一份,例如

public class JvmClass1 {

public static void main(String[] args) {

String c="java";

String d="abcd";

String e="java";

String f=new String("java");

}

}

运行时常量池 && 字符串常量池

class常量池被加载到内存后,形成了运行时常量池,Jdk1.7之前位于方法区中,Jdk1.8之后是放在元空间,或者把元空间看做是新的方法区。

运行时常量池相对于class常量池的一个特点是具有动态性,Java不要求所有常量在编译器产生,可以在运行时产生常量加入常量池,例如String类的intern()。

String.intern

intern源码的注解是Returns a canonical representation for the string object.,意思是返回字符串对象的规范表示形式。

第二段是A pool of strings, initially empty, is maintained privately by the class,说的就是字符串常量池,JDK1.6及以前是放在方法区中,后来放到了堆中,其中保存的是字符串对象的引用,而真正的字符串对象实例是在堆中创建。

第三段是

When the intern method is invoked, if the pool already contains a string equal to this {@code String} object

as determined by the {@link #equals(Object)} method, then the string from the pool is returned. Otherwise,

this {@code String} object is added to the pool and a reference to this {@code String} object is returned.

意思是当一个字符串对象调用intern方法,如果池中已经存在值相等(通过String的equal函数比较)的字符串常量,就返回常量池中的常量,也就是堆中对应实例的引用。否则将这个字符串加入常量池。

例如

public class JvmClass1 {

public static void main(String[] args) {

String a = "hello";

String b = new String("hello");

System.out.println(a == b);//false a和b是不同对象

String c = "world";

System.out.println(c.intern() == c);//true c.intern()返回的就是"world"在常量池中的引用,和c是同一个对象

String d = new String("mike");

System.out.println(d.intern() == d);//false d.intern()返回的类似a,而d类似b,不同对象

String e = new String("jo") + new String("hn");

System.out.println(e.intern() == e);//true 通过拼接得到的,并没有出现"john"的字面量,所以只有当e.intern()才加入池中,所以是同一对象

String f = new String("ja") + new String("va");

System.out.println(f.intern() == f);//false 有个博客说"java"在jvm启动时自动加入字符串常量池中,不过还没找到其他什么证据。

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值