new string创建了多少个对象?

时间:2018-05-23 05:19:46

标签: java string string-pool

如果我写下面的代码

场景-1 [最初在字符串常量池中没有值]

String s1 = new String("test"); 

然后创建了多少个对象?

根据我的回答: 创建了两个对象::一个是在字符串文字池中,另一个是因为new而在堆中 参考:refer link

为什么char []显示在refer link

场景-2 [最初在字符串常量池中没有值]

String s1 = "test";
String s2 = new String("test"); 

然后创建了多少个对象?

根据我的回答: 三个对象创建::一个在s1的字符串文字池中,第二个在堆中,因为s2为new,第三个为s [char [] 参考:refer link

我的回答是正确的?请给我一个确切的想法,哪一个是对的?

1 个答案:

答案 0 :(得分:0)

String s1 = new String("test"); 

JVM在堆上创建两个对象,在常量池中创建另一个对象。

String s1 = "test";  //Line 1
String s2 = new String("test"); //Line 2

第1行将在常量池中创建一个对象(如果尚未存在)。 第2行将仅在堆上创建,因为池中已存在一个

如果你看一下String类,你会发现它初始化了一个最终的char []来创建一个不可变对象,但那些仅限于实例化:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    .
    .
    .

    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = "".value;
    }

    .
    .
    .
}
相关问题