What I always try is to compile and see the result myself. I then insert 'printing'messages to try and trace the path that is being followed. However, in this case after compiling succesfully and trying to run it, I got this errormessage: Exception in thread "main" java.lang.NoSuchMethodError: main
The key point to this question is the call to System.gc(). When you call this method, you are asking for the JVM to run Garbage Collector. It will search for objects eligible for garbaging, and will call the finalize() method once in these objects. Note, however, that you can only suggest that the garbage collector should run, the JVM can completely ignore you, or can do just part of the work, there is no way for you to know. So back to the question, waht happens is that after the call to m1(), we will have A1A2A3A4 printed in the console, as you would have expected, and three objets eligible for garbage colleting, pointed by a1, a2 and a3 (note that a0 is not an object, just a reference to one). So the Garbage Collector will finalize none, any or all of these objects, calling its finalize()'s methods, which prints their names. Therefore, the answers a,c,d,e are all possible to happen. Running the example in my computer I always got answer d, A1A2A3A1A1A2A3, but this doesn't mean that the others are not possible. Hope this can be helpfull! Cheers!
posted 15 years ago
In a nutshell: you refer a1 to an A with value "A1" and an otherA with value "A2". Same goes for a2 (A2 & A3) and a3(A3 & A1). In the for-loop you ask of a0 to refer to the otherA value of the A it is referring to, thus creating a loop. If you increase the maxvalue of i in the for-statement (ie to 9), you'll see A1A2A3A1A2A3A1A2A3A1A2A3, the last A1A2A3-cycle always being created by finalize() (due to the garbage collection).
Am I right? It may be that I still mix-up terminologies, for that I apologize. (This is only my 7� week of Java...) [ October 27, 2004: Message edited by: Eric Zanders ]