2014-06-05 92 views
1

我对java字符串池有一些疑问。java字符串池中的内容

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

在上述情况下,

我的问题是一样的中间琴弦“欢迎”添加到池中与否。 例如,在我的思想,当前字符串池有内容如下

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

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

+1

专家3人,3个不同的答案,OK,现在只有两个答案。 –

+0

现在一个。 hehehe :) –

回答

1

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

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

因此存在由上述代码存储在池2个字符串:"welcome to java",和"HTML"

+0

在我学习的幻灯片中,他们只是说只有具有简写符号的字符串才会存储在字符串池中。那么你是说String对象来自正式定义,它也存储在String池中? – user3473222

+0

@ user3473222是的你是对的。使用'new'关键字创建的字符串将存储在Java堆中。只有带简写符号的字符串才会存储在Java堆中的字符串池中。 –

+1

@downvoter - 自己解释.. – TheLostMind

1

感谢JB Nizet FO这个.. :)

 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 
+0

为什么'System.out.println(s3 == s4);'给出'false'作为输出?是因为's3'是用其他变量初始化的,而不是简写和符号? –

+0

@MehmetSedatGüngör - 因为s3和s4是不同的。 S4在Stringpool上,而S3在堆上。 – TheLostMind