所以我正在学习 Kathy Sierra 书中的 SCJP。 在字符串章节中,这是一个问题:
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat( "fall ");
s2.concat(s1);
s1 += "winter";
System.out.println(s1+" "+s2);
---------------------------
What's the output, and how many string objects and ref variables are created?
输出是 spring winter spring summer 并且有两个引用变量,没问题。
然后它说创建了八个字符串对象(spring、summer、spring summer...等),包括由于没有引用它们而丢失的对象。
但是,它不包含上一个系统输出的任何内容。
我的问题是,在最后一行代码中,由于 s1 和 s2 是用空格连接的,这是否也创建了新对象?还是只是将其传递给字符串缓冲区进行显示,而不创建新对象?
这显然是非常基础的,我看了其他地方,但没有直接回答这个问题。据我了解,它也应该在那里创建新对象,但我需要确保考试!想法?
提前致谢!
最佳答案
My question is, in the last line of code, since s1 and s2 are being concat with a space, doesn't this also create new objects?
是的,它创建了第 10 个字符串。
请注意,这段代码本身只需要创建 5 个字符串——如果您在同一个 JVM 中多次运行它,每次调用它时都会创建 5 个新字符串。每次代码运行时,字符串文字不会创建一个新字符串。 (例如,每次 "spring "
都会重复使用相同的字符串对象。)
您提供的代码中有 10 个字符串:
- 5 个字面量:“spring”、“summer”、“fall”、“winter”和“”
- 5 个连接结果:
s1 + "summer"
、s1.concat("fall ")
、s1 + winter
(复合赋值) 和s1 + ""+ s2
。
正如我刚刚评论的那样,代码中出现的字符串文字总是 涉及一个单独的字符串。例如,考虑:
String x = "Foo" + "Bar";
您可能希望这涉及三个字符串对象 - 一个用于每个文字,一个用于串联。事实上,它只涉及一个,因为编译器在编译时执行连接,所以代码实际上是:
String x = "FooBar";
关于java - System.out.println 中使用的字符串是否也会创建新的不可变对象(immutable对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16690082/