1、题目
/**
* 演示字符串相关面试题
*/
public class Demo1_21 {
public static void main(String[] args) {
String s1 = "a";
String s2 = "b";
String s3 = "a" + "b";
String s4 = s1 + s2;
String s5 = "ab";
String s6 = s4.intern();
// 问
System.out.println(s3 == s4);
System.out.println(s3 == s5);
System.out.println(s3 == s6);
String x2 = new String("c") + new String("d");
x2.intern();
String x1 = "cd";
// 问,如果调换了【最后两行代码】的位置呢
System.out.println(x1 == x2);
}
}
2、解释
2.1、String s3 = "a" + "b"
1、常量池中的信息,都会被加载到运行时常量池中,这时 ab 是常量池中的符号,还没有变为java字符串对象。 2、ldc #2 会把ab符号变为 "ab" 字符串对象。 3、把得到的"ab"字符串对象去串池 StringTable[]中查找, 串池中没有,则把"ab"放入到串池中。
2.2、String s4 = s1 + s2;
2.3、String s6 = s4.intern();
s4.intern(): 将这个字符串对象尝试放入串池StringTable,如果有则不会放入。如果没有则放入串池StringTable,并且会把串池中的对象返回。