字符串池可以包含两个具有相同值的字符串吗?

时间:2013-07-31 10:23:08

标签: java string

字符串池可以包含两个具有相同值的字符串吗?

String str = "abc";
String str1 = new String("abc");

   Will the second statement with `new()` operator creates two objects of `string` "abc", one on `heap` and another on `string` pool? 

   Now if i call intern() on str1 ie str1.intern(); as a third statement, will str1 refer to the "abc" from String pool? 

  If yes then what will happen to the object that was created on heap earlier by the new(). Will that object be eligible for garbage collection.?
  If no then what will be the result of str1.intern();?

5 个答案:

答案 0 :(得分:6)

No first也将创建一个对象,第二个将只创建一个字符串对象。区别在于第一个将在String池中创建,第二个将仅在堆中创建。 如果您将调用 str1.intern(); ,则会将其添加到字符串池中。

String str1 = "abc";
String str2 = new String("abc");
Stirng str3 = "abc"

这里将创建两个对象。第一行将创建一个具有引用str1的强对象,第三行将指向在第一行中使用引用str3创建的同一对象,但在第二行中将创建一个新对象,因为我们在此处使用new关键字。希望它会对你有所帮助。

同时检查this回答。那里有很好的解释。

答案 1 :(得分:1)

new String("abc")是一个类实例创建表达式,必须创建一个新对象。它是否在内部与文字“abc”共享相同的char数组取决于String实现。 “abc”引用都将使用相同的实习生字符串。

答案 2 :(得分:1)

    String t1 = "ABC";
    String t2 = new String("ABC");
    String t3 = "ABC";

    System.out.println(t1 == t2);
    System.out.println(t2 == t3);
    System.out.println(t1 == t3);

生成以下输出(Java SE 7):

    false
    false
    true

答案 3 :(得分:0)

基本上是:

// "abc" is interned by the JVM in the pool
String str="abc"; 
// JVM uses the pooled "abc" to create a new instance
String str1=new String("abc"); 

String引用的只创建了一个新的str1对象。 String文字"abc"由JVM实施。由于文字"abc"已经存在于String池中,因此在第二个语句中,JVM应该使用它。

答案 4 :(得分:0)

“abc”对象将在类加载时创建并放在String池中。第二行将使用String(String original)构造函数,其中original是池中“abc”的指针。这是第二行的字节码:

NEW java/lang/String
DUP
LDC "abc"
INVOKESPECIAL java/lang/String.<init>(Ljava/lang/String;)V
ASTORE 2