答案是: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 objectss1.concat("fall "); //Two references and 5 objectss2.concat(s1); //Two references and 6 objectss1 += "winter "; //Two references and 8 objectsSystem.out.println(s1 + " " + s2);现在的问题是: Java如何处理内存中的String对象?
Java提供了两种创建类对象的方法
String。
- 字符串str1 =“ OneString”;
在这种情况下,JVM搜索字符串池以查看是否已经存在等效字符串。如果是,则返回相同的引用。如果不是,则将其添加到字符串池并返回引用。
因此,可能会创建一个新对象,也可能不会。
- 字符串str1 = new String(“ OneString”);
现在,JVM必须在堆上创建一个对象。由于 新 。
OneString字符串池中是否已存在都没关系。
您还可以将字符串放入池中:
您可以在String对象上调用intern()。如果尚未将String对象放入池中,则将其放入池中,并将对池字符串的引用返回。(如果它已经在池中,则只返回对该对象的引用)。
您可能希望查看以下链接:
什么是Java字符串池?“ s”与新的String(“
s”)有何不同?
有关Java的字符串池的问题



