我被问到这个问题:
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*
根据以上细节,在下面代码的 println 语句之前创建了多少个 String 对象和多少个引用变量?
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
我的回答是这段代码片段的结果是春冬春夏
有两个参考变量,s1 和 s2。一共创建了八个String对象,分别为:“spring”、“summer”(丢失)、“spring summer”、“fall”(丢失)、“spring fall”(丢失)、“spring summer spring”(丢失) )、“winter”(丢失)、“spring winter”(此时“spring”丢失)。
在这个过程中,八个 String 对象中只有两个没有丢失。
这是对的吗?