-4

我正在阅读这本 SCJP-Kathy sierra 的书(来自哪个问题),我引用了那本书的第 432 页

创建新字符串

 Earlier we promised to talk more about the subtle differences between the various
    methods of creating a String. Let's look at a couple of examples of how a String
    might be created, and let's further assume that no other String objects exist in the
    pool:
    String s = "abc"; // creates one String object and one
    // reference variable
    In this simple case, "abc" will go in the pool and s will refer to it.
    String s = new String("abc"); // creates two objects,                   Line X
    // and one reference variable
    In this case, because we used the new keyword, Java will create a new String object
    in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
    be placed in the pool.

为什么它在第 X 行(在注释中)说它创建了两个对象

4

1 回答 1

4

如果你有

String s = new String("asdf"); 

并且"asdf"没有在其他任何地方引用然后它创建了两个对象。一个"asdf"在 perm gen 区域的字符串池内,一个new String("asdf")在普通堆中。

于 2013-06-20T12:37:06.687 回答