当一个String实例str调用intern()方法时,Java查找常量池中是否有相同Unicode的字符串常量,如果有,则返回其的引用, 如果没有,则在常量池中增加一个Unicode等于str的字符串并返回它的引用。
常量池(constant pool)指的是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量。
测试:
public static void main(String[] args) {
String s1 = "";
for (int i = 1; i <= 3; i++) {
s1 += new String("" + i);
}
String s2 = 1 + "2" + "3";
String s3 = "123";
System.out.println(s1 + " " + s2+" "+s3);
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s1 == s3);
s1 = s1.intern();
System.out.println(s1 + " " + s2+" "+s3);
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s1 == s3);
}
结果:
========
123 123 123
false
true
false
123 123 123
true
true
true
========
1. s1.intern() == s1的原因:
s1.intern()会在常量池中查找"123"字符串,如果没有找到,则将"123"放入常量池中,但不会改变s1的引用,也就是此时存在两个"123"。
2. s2 == s3的原因:
s2是多个常量的组成,可以在编译器解析为一个字符串常量,所以s2是常量池中"123"的一个引用