From the following code how many objects are eligible for garbage collection? String string1 = "Test"; String string2 = "Today"; string1 = null; string1 = string2; A) 1 B) 2 C) 3 D) 0 I think answer is 1 but i'm confused. Can somebody give me the explanation. Thanks Ash
Hi Ash sav! In my opinion the answer is D.i.e no object is created here and so none is there for GC. Since String s="not new"; does not create a new string object it takes the one available in the pool or create a new String literal if it's not in the pool. so whenever we create strings without a new operator, no object is created and so GC does'nt come in. Am i correct Jane!if not correct me.please .
hi i thing in this case even thoug any object is not created using new operator but still memory is allocated to test and today so two objects r in memory but when we say s1=null;means now there is no variable or no way to access memory allocate for test so it is redy for gc and today is pointed by s1 and s2 so no question of it to be gcollected so i thing ans is only one object i.e A ..praful
All desirable things in life are either illegal, banned, expensive or married to someone else !!!
Hi Ash, Nachiket, For the purpose of doing the mock exams, assume gc works on String literals (they all seem to be written that way ) .. which means you're right Ash, 1 object is eligible. Two strings are created, "Test" and "Today". When string1 is set to 'null' the object "Test" is no longer being referenced. string2 references "Today"; so when string1 is set to equal string2 it will also be pointing to the string object "Today". Remember that on the exam you probably will only get 1 question on gc and it not apt to involve String literals. The key is to understand how reference type variables work vs primitive variables and that a reference variable set to 'null' no longer points to any object. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform