tags:

views:

129

answers:

3
public class App1 
{

 public static void main(String[] args) 
 {
   Point point_1 = new Point(5,5);
   Point point_2 = new Point(7,8);
   Circle circle_1 = new Circle(point_2, 10);
   point_1 = null;
   point_2 = null;
 }
}

How many object references exist after this code has executed? Why?

+7  A: 

After this code has executed, exactly none, since it will have exited :-)

If you mean at the point just before exit, there's a reference on the stack to your circle and a reference in your circle to the second point, assuming the constructor stores it.

paxdiablo
Minor point: The compiler might not bother to put circle_1 on the stack since it is an unused local.....
mikera
+5  A: 

The answer is:

  1. Define what you mean for an object reference to "exist".
  2. It is impossible to know how many object references were even created, without details of the Point and Circle classes.
  3. The answer is irrelevant, because after the main method exits none of the objects will be reachable ... whether or not the references still "exist".

We might infer that at the point in time immediately before the main method returns there will be one reachable reference to a Circle object and one reachable reference to a Point. But one has to make some (reasonable) assumptions about how those two classes are implemented to make that inference. (For example, one has to assume that the respective constructors don't add the Point and Circle reference to some static data structure.)

Are objects cleaned up when references to them are nulled?

No. Objects are cleaned up when the garbage collector runs, and it determines that the objects in question are no longer reachable. In this sense, "reachable" means that you can get to the object by following a chain of references to the object starting from:

  • a static attribute of some class
  • a local variable of some method that is currently being executed by some thread
  • an attribute of some other reachable object, or
  • an element of some other reachable array.

(I've simplified the explanations of GC and reachability a bit to avoid confusing the OP with things he/she won't understand yet.)

Stephen C
+7  A: 
polygenelubricants
Hey, that's cool. What did you use to do those diagrams?
paxdiablo
@paxdiablo: yuml.me ; see also http://meta.stackoverflow.com/questions/55442/web-apps-to-make-your-answers-awesomer
polygenelubricants
Wow, your answers keep getting cooler, keep it up! You'll be giving Jon Skeet a run for his money soon enough. :P
Andrei Fierbinteanu
Awesome Answer!
sixtyfootersdude