0

如果我写下面的代码

场景一【字符串常量池中最初没有值】

String s1 = new String("test"); 

那么创建了多少对象?

根据我的回答:创建了两个对象 :: 一个在字符串文字池中,另一个在堆中,因为新引用:参考链接

为什么 char[] 显示在参考链接中

场景二【字符串常量池中最初没有值】

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

那么创建了多少对象?

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

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

4

1 回答 1

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

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

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

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

如果您查看 String 类,您会发现它初始化了一个 final 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;
    }

    .
    .
    .
}
于 2018-05-23T05:24:30.800 回答