LOST String 对象会发生什么
Line 1: String x = "Java";
Line 2: x.concat(" Rules!");
Line 3: System.out.println("x = " + x);
输出为“x= Java”
第 1 行:创建一个新的 String 对象,给出值“Java”,并将 x 引用到它。
第 2 行:VM 创建第二个 String 对象,其值为“Java Rules!”但没有任何提及它。第二个字符串对象立即丢失;你无法到达它。
由于这些字符串对象是在堆中创建的,因此第二个对象将被垃圾收集。
Line 1: String x = "Java";
Line 2: x.concat(" Rules!");
Line 3: System.out.println("x = " + x);
Output is "x= Java"
Line 1:creates a new String object, gives the value "Java", and refer x to it.
Line 2: VM creates a 2nd String object with value "Java Rules!" but nothing refers to it. THE 2nd STRING OBJECT IS INSTANTLY LOST; YOU CANNOT GET TO IT.
As these String Objects are created in Heap, will the 2nd object be Garbage Collected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Enosh,在java中字符串是不可变的,所以你应该
为第二行分配,然后它就会工作。
第二个对象最终将被 GC,因为不再有实体引用它。
Enosh, in java Strings are immutable, so you should assign
for the second line and then it will work.
The second object will be GC'd eventually because there is no longer an entity refering to it.
绝对地。这就是垃圾收集的全部意义。
Absolutely. That's the whole point of garbage collection.
同意所有其他人的观点,即它会被垃圾收集。但我猜编译器可以在编译期间完全删除它,因为 concat 方法只影响方法局部字段,因此整个语句没有意义。
Agree with all the others that it get garbage collected. But I guetss that the compiler can remove this at all during compilation as the concat methods does only affect method local fields and therefor the whole statement doesn't make sense.