深⼊理解newString()
onestepatatime⼀、引⾔
new String("hello")这样的创建⽅式,到底创建了⼏个String对象?
⼆、分析
1 String s1 = "HelloWorld";
2 String s2 = new String("HelloWorld");
3 String s3 = "Hello";
4 String s4 = "World";
样young歌词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⽤来返回常量池中的该字符串,如果常量池中已经存在该字符串,则直接返回常量池中该对象的引⽤。否则,在常量池中新建⼀个对象,然后返回引⽤。