Originally posted by Jo Liang:
How many objects are candidates for garbage collection by the end of the following code sinppet:
1.String s = "Hello"; //1
2.s = "Hello" + " World";//2
3.System.out.println(s.toUpperCase());//3
A) 1
B) 2
C) 3
D) 4
E) none
This answer is B.
Can somebody explain why? Thanks
Hello Jo,
I think the answer shd be 'a' ie. only 1 object...
Have a look at code sequence...(to which i have given number)
1. at line 1,
String literal "Hello" is created in literal pool
2. at line 2 Compiler sees that "Hello" is already present in literal pool. so it doesn't create it. Only String literal"World" is created
in pool
Now at runtime, because
+ operator, a string object is created on heap. ie. String object containing "HelloWorld"
3. Now at line 3, because of function to
UpperCase() new string object containing "HELLOWORL" is created.
Now s is refering to the above object . so the previous object (containing "Hello World") is unreferenced now. so it can be garbage
collected.
Here 2 obejct in string pool and 2 in heap r created. and s refers to one of the heap object
so only one remains for garbage collection. String literals r never garbage collected.
Correct me if i am wrong