Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to LOST String objects

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.

like image 474
Enosh Bansode Avatar asked Aug 16 '11 06:08

Enosh Bansode


2 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.

like image 99
Dorpsidioot Avatar answered Oct 31 '22 19:10

Dorpsidioot


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

like image 37
Michael Lorton Avatar answered Oct 31 '22 20:10

Michael Lorton