Take the 2-minute tour ×
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.

share|improve this question
Note that "x = "+x creates a third String. –  Thilo Aug 16 '11 at 7:00
add comment

3 Answers

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.

share|improve this answer
The question was not about making something work - Enosh wanted to know what happens to the result String of the concat operation - whether it's created and stored somewhere or not. –  Andreas_D Aug 16 '11 at 6:57
Yes I know, but I'd rather fix the error, so that people who look at this question, don't get mistaken. –  Dorpsidioot Aug 16 '11 at 7:14
add comment

Absolutely. That's the whole point of garbage collection.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


