JVM - intern()

s = "sss";

s.intern() 返回的是字符串s在字符串常量池中的引用。
首先判断字符串常量池中是否有 “sss” 如果有则返回其引用地址
如果没有则创建一个然后返回 sss 的引用地址

public static void main(String[] args) {
    String s = new String("1");
    s.intern();
    String s2 = "1";
    System.out.println(s == s2); //false

    String s3 = new String("1") + new String("1");
    s3.intern();
    String s4 = "11";
    System.out.println(s3 == s4); //true
}

String s3 = new String(“1”) + new String(“1”); ——> s3 引用对象的内容是 “11”,但是常量池中并没有 “11”
s3.intern(); 将 “11” 加入到常量池中,并使用 s3 的引用作为后续字符串 "11"的引用地址。
添加堆中“11”对象的引用到字符串常量池

字面量和非字面量不同:

String s1 = new String(“1”);//字面量 “1”,会放到字符串常量池中
String s2 = new String(“1”) + new String(“1”);// "11"不会放进常量池
s2.intern() // 将"11"对象的引用添加到常量池中

字符串常量池:

  1. 存储引用

使用intern(),默认将字符串对象的引用加入常量池(String s2 = new String(“1”) + new String(“1”))

  1. 存储字面量

字面量 == “1”,也就是写出来的,都会放到常量池

Q:String s1 = new String(“1”) + new String(“1”);创建了多少对象?
A:四个,分别是字符串常量池中创建 “1”,两个new ,以及一个 new String(“11”)对象.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值