String面试题
1.String.intern()方法返回常量池中和String对象的值相同的常量的引用,如果常量池中没有该常量,则把该String对象的值加入常量池
String s1 = "programming";
String s2 = new String("programming");
String s3 = "program";
String s4 = "ming";
String s5 = "program" + "ming";
String s6 = s3 + s4; // s6指向新的对象
System.out.println(s1 == s2); // false
System.out.println(s1 == s5); // true
System.out.println(s1 == s6); // false
System.out.println(s1 == s6.intern()); // true
System.out.println(s2 == s2.intern()); // false
System.out.println(s1 == s2.intern()); // true
System.out.println(s6 == s6.intern()); // false
String str1 = "str";
String str2 = "ing";
String str3 = "str" + "ing";//常量池中的对象
String str4 = str1 + str2; //在堆上创建的新的对象
String str5 = "string";//常量池中的对象
System.out.println(str3 == str4);//false
System.out.println(str3 == str5);//true
System.out.println(str4 == str5);//false