深入理解new String()

一、 引言

new String("hello")这样的创建方式,到底创建了几个String对象?

二、 分析

 1 String s1 = "HelloWorld";
 2 String s2 = new String("HelloWorld");
 3 String s3 = "Hello";
 4 String s4 = "World";
 5 String s5 = "Hello" + "World";
 6 String s6 = s3 + s4;
 7 
 8 System.out.println(s1 == s2);
 9 System.out.println(s1 == s5);
10 System.out.println(s1 == s6);
11 System.out.println(s1 == s6.intern());
12 System.out.println(s2 == s2.intern());//false true false true false

 

1. String s1 = "HelloWorld";

  去常量池查找,有则指向该地址,没有则在常量池创建后指向该地址。

  常量池:JDK7以后,从方法区,移到了堆中。

2. String s2 = new String("HelloWorld"); 

  • "HelloWorld" 去常量池查找,若有则返回该引用,没有则在常量池创建对象后返回该引用
  • 在堆里创建一个String对象

3. String s5 = "Hello" + "World";

  将"Hello" 与 "World" 拼接以后的"HelloWorld" 赋值给s5

4. String s6 = s3+s4;

  等价于 s6 = new String (s3+s4);

三、Intern

  intern用来返回常量池中的该字符串,如果常量池中已经存在该字符串,则直接返回常量池中该对象的引用。

  否则,在常量池中新建一个对象,然后 返回引用。

转载于:https://www.cnblogs.com/yumingxing/p/9434947.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值