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.
Enosh, in java Strings are immutable, so you should assign
x = x.concat(" Rules");
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.
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.
精彩评论