java String池中的内容

时间:2014-06-05 06:46:30

标签: java string

我对java String pool有一些疑问。

String s1 = "welcome" + " to" + " java";
String s2 = new String("HTML");

在上述情况下,

我的问题是中间字符串如“欢迎”加入池中或不加入。 例如,在我看来,当前的String池的内容如下所示

"welcome"
" to"
"welcome to"
" java"
" to java"
"welcome to java"

如果我的想法错了,请告诉我。

2 个答案:

答案 0 :(得分:1)

编译器将多个常量字符串视为单个字符串。因此上面的代码类似于

String s1 = "welcome to java";
String s2 = new String("HTML");

上面的代码在池中存储了2个字符串:"welcome to java""HTML"

答案 1 :(得分:1)

感谢JB Nizet为此...... :)

        String s1 = "Hellothere";// Hellothere added to SP
        String s2 = "Hello" + "there"; //Hellothere "already" present in SP
        System.out.println(s1 == s2); // true. And yes, I am intentionally comparing Strings using"=="
            String s3 = s1 + s2;
        String s4="HellothereHellothere";
        System.out.println(s3==s4);//False.. HellothereHelloThere NOT added to SP