Java如何处理内存中的String对象?

cod*_*_15 6 java string scjp

有人问我这个问题:

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,
                 // and one reference variable*
Run Code Online (Sandbox Code Playgroud)

基于以上细节,在下面的代码的println语句之前创建了多少个String对象和多少个引用变量?

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
Run Code Online (Sandbox Code Playgroud)

我的回答是这个代码片段的结果是春冬春夏

有两个参考变量,s1和s2.共创建了八个String对象:"spring","summer"(lost),"spring summer","fall"(lost),"spring fall"(lost),"spring spring spring"(丢失) ),"冬天"(丢失),"春天的冬天"(此时"春天"丢失).

在此过程中,八个String对象中只有两个不会丢失.

这是对的吗?

Azo*_*ous 4

答案是:2 个引用和 8 个对象。

String s1 = "spring "; //One reference and 1 object in string pool. (if it didn't exist already)

String s2 = s1 + "summer "; //Two references and 3 objects

s1.concat("fall "); //Two references and 5 objects

s2.concat(s1); //Two references and 6 objects

s1 += "winter "; //Two references and 8 objects

System.out.println(s1 + " " + s2);
Run Code Online (Sandbox Code Playgroud)

现在你的问题是:Java如何处理内存中的String对象?

Java提供了两种创建类对象的方法String

  1. 字符串 str1 = "OneString";

在这种情况下,JVM 会搜索字符串池以查看是否已存在等效字符串。如果是,则返回对同一对象的引用。如果没有,则将其添加到字符串池并返回引用。因此,可能会创建一个新对象,也可能不会。

  1. 字符串 str1 = new String("OneString");

现在,JVM 必须在堆上创建一个对象。由于新的. OneString字符串池中是否已经存在并不重要。

您还可以将字符串放入池中:

您可以对 String 对象调用 intern()。如果 String 对象尚不存在,这会将 String 对象放入池中,并返回对池字符串的引用。(如果它已经在池中,它只返回对已经存在的对象的引用)。

您可能想查看以下链接:

什么是 Java 字符串池?“s”与 new String(“s”) 有何不同?

关于Java字符串池的问题