This decission is taken by the garbage collector itself, the condition for an object to be collected is made upon the number of references to it. So if an object does not have any references it becomes candidate to collection.
That does not mean that it is inmediatelly collected, just a candidate to collection.
The object collection is governed by the generations mechanism:
An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data.
Concerning your code, the object created in the first line MyClass mc = new MyClass();
becomes a candidate to collection right after the execution of the third one mc=null; //line2
Following the same pattern, the new object created at line3
(I don't think however that line makes what you think it does: Shouldn't that line be mc = new MyClass();
?) becomes a candidate after the execution of line 5.
Note that even though you remove line2
, the first object will be elegible for collection because it is not referenced any longer.