如何区分String的实例指向堆还是常量池中

最近看JVM的时候,看到一个很有意思的题目,如下

String s1 = new String("111");
String s2 = "111";
String s3 = s1.intern();

System.out.println(s1 == s2);
System.out.printlin(s2 == s3);
第一个返回的结果是false
第二个返回的结果是true

s1实例指向的是堆,s2指向的是字符串常量池,s1的intern()方法并不会将原本指向堆内存的s1,改为指向常量池,而是复制一个s1的副本指向常量池中,intern()方法也有注释

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

当intern()方法被调用,如果池中已经有了这个String对象,那么直接返回,另一方面如果没有那么就将这个String对象添加到池中,并返回这个字符串的引用。
在这里插入图片描述
另外知识补充:
java中基本类型的包装类的大部分都实现了常量池技术,即Byte,Short,Integer,Long,Character,Boolean。这5种包装类默认创建了数值[-128,127]的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。 两种浮点数类型的包装类Float,Double并没有实现常量池技术。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值