This is a Question from danchisholm's website(http://www.danchisholm.net/july21/guide/chapter8/exam1.html). I do not agree with the answers provided...because i understand the finalize() for each object will be called only once and so the answer should be: A1 A2 A3(or any combination of this) !!!
Which of the following could be a result of attempting to compile and run the program?
a. A1A2A3A1 b. A0A0A0A0A1A2A3 c. A1A2A3A1A2A3 d. A1A2A3A1A1A2A3 e. A1A2A3A1A3A2A1 f. A0A1A2A3A1A2A3
The Answer is :
a. A1A2A3A1 c. A1A2A3A1A2A3 d. A1A2A3A1A1A2A3 e. A1A2A3A1A3A2A1 Explaination : The three instances of class A form an isolated ring where each instance references the next instance and the third references the first instance. Four iterations of the for loop are processed. Inside the body of the for statement, the invocation of the print method contains the argument expression a0 = a0.other(). On the first iteration, the reference variable a0 references the instance named A3. The value returned by the method named other is a reference to the instance named A1. The reference is assigned to the reference variable a0 and is also the value produced by the expression a0 = a0.other(). That reference value is passed as an argument to the print method, and the print method invokes the A.toString method. With each iteration of the loop, the reference moves to the next object in the loop and the name of the object is printed. After four iterations, the loop ends and the method m1 returns. The invocation of the System.gc method serves as a suggestion that the garbage collector should be allowed to run. The system could ignore the suggestion, so there is no guarantee that the eligible arguments will be garbage collected. If they are collected, there is no guarantee which will be collected first. The only guarantee is that the finalize method will be invoked on each particular instance before the resources that had been allocated to that instance are reclaimed.
( tags added) [ November 24, 2004: Message edited by: Barry Gaunt ]
The answer should be a, c , d, e. Explain below: in method m1(), it created three local variable a1,a2,a3. a0 points to the same object as a3 first. when you ran the for loop a0 will point to in the order of object A1,A2,A3,A1. so the output for sure will have A1A2A3A1. afer m1() returns, those local reference variable a1,a2,a3,a0 expired, so the objects they point to are eligible for collection. then run System.gc(), Remember running System.gc() just requires JVM to collect gargabe. it is not guranteed whether it will collect or not and in which order it will collect. Although there are three objects eligible to collect, it may collect one or two(answer c) or three ( answer d, e) or none( answer a) of them.