是否使用+串联创建的字符串存储在字符串池中?

Osc*_*Ryz 10 java string language-features

例如

 String s = "Hello" + " World";
Run Code Online (Sandbox Code Playgroud)

我知道池中有两个字符串"Hello"和"World"但是,"Hello World"进入字符串池吗?

如果是这样,怎么样?

String s2 = new String("Hola") + new String(" Mundo");
Run Code Online (Sandbox Code Playgroud)

每种情况下池中有多少个字符串?

dan*_*ben 11

是的,如果a String是通过连接两个String 文字形成的,那么它也将被实习.

来自JLS:

因此,测试程序由编译单元组成(第7.3节):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }
and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }
Run Code Online (Sandbox Code Playgroud)

产生输出:

true
true
true
true
false
true
Run Code Online (Sandbox Code Playgroud)

重要的行是4和5. 4表示你在第一种情况下要求的内容; 图5显示了如果一个不是文字(或更一般地,编译时常量)会发生什么.

  • 在第一种情况下,只有一个字符串文字,因为编译器已经选择了前两个字符串.如果查看compiles类文件,则只有一个String文字. (4认同)

Bri*_*new 4

我相信在第一种情况下,编译器会很聪明,并将连接的字符串放入池中(即,那里只有1个字符串)