Hu guys. Here I found this exercise that anyway i'm not 100% sure that it's wrong. You can find it in page 30 exercise 48.
Which of the following is not a possible output of this code, assuming it runs to completion.
What this book says in the answers section about this point is: "If it runs right at the end of the main() method, Option D would be output.
So, on the other hand, according to the book right answer is option A. But for me it should options A and D because in regards the book "OCA study guide" from same authors in page 38 about finaleze() method it says:"Just keep in mind that it might not get called and that it definitely won't be called twice".
So I guess that there is no way whereby option C could be correct.
Pablo Napoli wrote:... in regards the book "OCA study guide" from same authors in page 38 about finaleze() method it says:"Just keep in mind that it might not get called and that it definitely won't be called twice".
I don't have the book but I suppose that sentence is referring to the finalize() method of a particular object. There are two Toy objects in that code, and yes, the finalize() method of each object definitely won't be called twice. So that amounts to at most two times when "clean-" will be printed.
posted 3 weeks ago
Hi Paul. Thanks for your answer. I thought that finalize() does not depend on each object but of the thread of the process, so i took for grantes that it cannot be called twice.
I presume that exercise is written for the Java8 exams, i.e. before Object#finalize() was deprecated. Both the book and the practice exams are written on the assumption that you will read the documentation, which says,
The finalize method is never invoked more than once by a Java virtual machine for any given object.
That means you can write myObject.finalize(); but otherwise finalize() is never called twice on the same object. The quote from the book you showed us tells us the same.
There is nothing in that code likely to cause any exceptions to be thrown. That means you can expect it to run to completion at the end of main(), so there will be two xxx.play() calls, which means, “play−” will appear twice. That means option A can't occur, so A is part of the answer.
The fact that you call System.gc(); in line 11 does not necessarily mean that garbage collection (=GC) will occur. It is a suggestion to the JVM not an instruction. So it is possible for, “play−play−”, or, “play−play−clean−” to be printed, so C can occur, which leaves only D to be considered as a possible answer.
When you get to line 13, the doll reference won't be garbage collected. You have at this point an almost empty heap, so even if doll is eligible for GC nothing will happen. The only way you could get “clean−” twice would be to write xxx.finalize() somewhere. Remember the JVM never calls finalize() twice on the same object.
For my next feat, I will require a volunteer from the audience! Perhaps this tiny ad?