You are right. It should be 0. Who gave the question saying it is 1 ? By the way, if a sting is created with new instead of a direct assignment like this : String s = new String("Hello"); Is it a candidate for GC ? Thanks.
I think that the only kind of object that is liable to be GCed is object. Things like instance of a class or array. So, Integer the wrapper class type could be GCed while int won't be. I think that string literal are kept in string constant pool, which is not subjected to GC therefore the answer should be zero. As for string created using new, that would be creating an object of String type and so it should be eligible for GC. Correct me if I am wrong. I got these from Passport series on Java 2. It also says that a lot of mock exam asks this types of question and that for the purpose of taking them assume string literal could be GCed. Hope this helps.
The answer is 1 object eligible for GC! String string1 = "Test"; String string2 = "Today"; string1 = null; string1 = string2; after the assignments, then there is no reference pointing to Test. therefore "Test" is eligible for GC. since both string1 and string2 point to the same object i.e. Today!
Joined: Jun 21, 2002
Um...I read somewhere that the only memory space that GC takes care of is the heap which contains only object and array. So, since string literal is contained in string constant pool that is not considered to be inside of the heap, string literal were not suppose to be 'recycled' by GC. Would some one check this out?