搞懂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用来返回常量池中的该字符串,如果常量池中已经存在该字符串,则直接返回常量池中该对象的引用。

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

猜你喜欢

转载自www.cnblogs.com/yumingxing/p/9434947.html
今日推荐