posted 23 years ago
Hi all:
First of all, the questions appearing in Sun exam will be worded properly - this is what I can say from my experience. That is, if a statement such as b1=b2 or ob1=ob2 appears in a question, then surely there will be a mentioning of what b1, b2, ob1,ob2 etc are.
Next, consider the case
String s1 = new String("s1"); //1
String s2 = new String("s2"); //2
s1 = s2; //3
s2 = null; //4
System.out.println("s1="+s1+", s2="+s2);
Here at //1, a String object with value "s1" is created and the reference variable s1 is made to point to it. Similarly at //2, another String object with value "s2" is created and the reference variable s2 is made to point to it.
Now in //3, s2 is assigned to s1. This means both s1 and s2 now point to the second object created in //2. So the first object created at line //1 has no reference pointing to it and it is now eligible for garbage collection.
At //4, s2 is assigned null. So s2 no longer points to the second object created at //2. But s1 STILL POINTS to this. So after the execution of line //4, no new object is available for garbage collection.
It is important to understand that term "eligiblity for garbage collection" applies only to objects and not to object references or other variables.
So in the following case
ob1=ob2;
ob2=null;
even if it is mentioned that ob1, ob2 are reference variables, actually we do not speak of the eligibility of ob1 and ob2 for garbage collection. Rather we speak of the eligiblity of the objects referred to by these variables ob1 and ob2 for garbage collection.
Now, if the question is as follows:
Consider the following code:
Object ob1=new String("one");
Object ob2=new String("two");
ob1=ob2; //line 1
ob2=null; //line 2
Does the object referenced by ob1 become eligible for garbage collection?
Then the answer is YES. But it is very important note that the object referenced by ob1 becomes eligible for garbage collection, at //line 1 when ob2 is assigned to it and NOT when ob2 is assigned null at //line 2!
Hope this explanation is clear.
Gaja Venkat
Sun Certified Programmer for Java 2 Platform
[This message has been edited by Gaja Venkat (edited September 13, 2001).]