mr.cazurro greenlins wrote:I know c2 is not null, but c3 is null, as c1.
so everything that applies for c1, applies for c3 so 4 objects are eliglible for garbage collector...
I dont know why you say that everything that applies for c1 applies for c3?
First of all only 2 CardBoard objects are created. c1 refers to one and c2 to the other.
CardBoard c3 = c1.go(c2)
calls method go with reference c2. That means inside the method cb will refer to the same object as c2. But since Java applies pass-by-value(!) the only thing that happens with the line cb = null; is that cb no longer refer
to the same object as c2.
c2 will remain untouched after the methodcall and still refer to the same object as it did before you invoked go().
You can replace the line
Here you are creating a variable c1 and c2 which refer to two CardBoard objects in memory.
Then you call c1's go method and pass the c2reference to it.
Now lets look at the go method!!
It takes the c2 as its parameter and set it to cb. and cb = null. Therefore c2 also null??....
c2 and the cb in your go method both refer to the same Cardboard object in memory. Therefore, although the cb = null; the object cardboard is still referred by the c2.
The method returns a null reference and assigns it to c3.
Then you set c1 to null. So there is no longer a reference to the Cardboard object created by c1. Now that is an object eligible for garbage collection.
Short is a Wrapper class. So you have a Short Object which was residing in c1. That i another object eligible for GC
SO 2 OBJECTS ARE ELIGIBLE FOR GARBAGE COLLECTION.
TIP: take a sheet of paper and draw the objects in the memory and how they are referred. Don't forget objects created within the class(such as Short in this question.). You will approach the answer comfortably!!