Janki Shah wrote:public class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb)
{
cb = null; //# 0
return cb;
}
public static void main(String[] args) {
CardBoard c1 = new CardBoard(); //line a
CardBoard c2 = new CardBoard(); //line b
CardBoard c3 = c1.go(c2); // # 1
c1 = null;
//doStuff
}
}
How many objects are created and how many objects are eligible for GC? And Also, I don;t understand what is actually happening at line # 1?
Can someone help me with this question, please?
1. First of all, how many objects are created on line a and line b? I would say four, the cardboard on line a , its Short story object is autoboxed and the cardboard on line b and its Short story object.
2. What happens to line #1 ? c2 variable is passed to go method. c2 variable refers to the object created in line b. In the method, cb variable refers to the object created in line b. But cb then refers to null in line #0. The null reference is returned and therefore c3 refers to null. After line #1, nothing is eligible for GC. It is because c3 refers to null reference.
If I change the code a little bit like this:
After line #1 , the object created in line c will be eligible for GC because it was refered by c3 once. But at line #1, c3 variable refers to null.
3. Ok...after digesting my 1 and 2, let's go back to this example again:
When the line //do stuff is reached, c1 variable now refers to null. The object created in line a has no variable refering to it. So, it will be eligible for GC as well as its Short story object. So, 2 objects will be eligible for GC at this line.
The object created in line b is not eligible for GC because c2 variable is still refering to it.
4. When the main method finishes, the objects created in line b will be eligible for GC.
For the exam, pay attention to the difference between object created in a line and its variable reference. I think most people including me always get confused by these two terms.
The object created and its variable reference are two different things. As long as the object created has no variable refering to it, it will be eligible for GC.