This is a question from Dan Chisholm's practice exams.
class A {
private
String name;
private A otherA;
public A(String name) {this.name = name;}
public void other(A otherA) {this.otherA = otherA;}
public A other() {return otherA;}
public String toString() {return name;}
protected void finalize() {System.out.print(name);}
}
class B {
public static void m1() {
A a1 = new A("A1"), a2 = new A("A2"), a3 = new A("A3"), a0 = a3;
a1.other(a2); a2.other(a3); a3.other(a1);
for(int i = 0; i<4; i++){System.out.print(a0 = a0.other());}
}
public static void main(String[] args) {m1(); System.gc();}
}
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 differs from his website and his book. His book states to select 3, while the website allows for 4 answers. The website answer is ACDE and the book's answer is ADE
The printed answer is the same for both the book and website:
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.
The last line appears to state that the answer "C" can't be correct and that the answer on the website is wrong. That either ALL instances are finalized at once or nothing is. Do I understand this correctly??