知识点
1、String s = "";会直接在常量池中创建该字符串
2、String s = new String("s");会创建两个对象,1是常量池中s,2是队中的new String("s")对象
3、intern()会判断这个字符串在不在字符串池中,如果不在则将当前字符串其加入到字符串池中

public static void main(String[] args) {

String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);

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

}

jdk6 false false
jdk7 false true
解释:
jdk6 :String s = new String("1");在堆中和字符串池中都创建了一个对象。s执行堆中的对象
s.intern()判断1已经在字符串池中了
String s2 = "1";创建了一个引用,直接指向字符串池中的1
s和s1指向不同的对象所以false
String s3 = new String("1")+new String("1");堆中创建了11以及字符串池中创建了1。s3指向堆中11
s3.intern();在字符串池中创建11
String s4 = "11";由于字符串池中已经有11了,s4直接指向11
所以s3=s4为false;

jdk7:String s = new String("1");在堆和字符串池中创建一个对象
s.intern();
String s2 = "1";创建了一个引用,直接指向字符串池中的1
s和s2为false;
String s3 = new String("1")+new String("1");堆中创建了11以及字符串池中创建了1。s3指向堆中11
s3.intern();常量池中不存在11,就将当前字符串的应用放入到常量池中
String s4 = "11";由于字符串池中已经有11了,s4直接指向常量池中11的引用
所以s3=s4为true;

public static void main(String[] args) {

String s = new String("1");
String s2 = "1";
s.intern();
System.out.println(s == s2);

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

}
jdk6:false,false
jdk7:false,false
解释:
jdk6 :String s = new String("1");在堆中和字符串池中都创建了一个对象。s执行堆中的对象
String s2 = "1";创建了一个引用,直接指向字符串池中的1
s.intern()判断1已经在字符串池中了
s和s1指向不同的对象所以false
String s3 = new String("1")+new String("1");堆中创建了11以及字符串池中创建了1。s3指向堆中11
String s4 = "11";在字符串池中创建11,s4直接指向11
s3.intern();在字符串池中创建11
所以s3=s4为false;

jdk7:String s = new String("1");在堆和字符串池中创建一个对象
String s2 = "1";创建了一个引用,直接指向字符串池中的1
s.intern();
s和s2为false;
String s3 = new String("1")+new String("1");堆中创建了11以及字符串池中创建了1。s3指向堆中11
String s4 = "11";在字符串池中创建11,s4直接指向11
s3.intern();
所以s3=s4为false;


yinpursue
1 声望0 粉丝