The following code has taken from "OCA/OCP JAVA SE 8 PROGRAMMER PRACTICE TEST" book Chapter 2 - Working with Java Data Types
Query: There are two possible answers
"48. Which of the following is not a possible output of this code, assuming it runs to completion?
on page 437
"48. A. Remember that garbage collection is not guaranteed to run on demand. If it doesn’t run at all, Option B would be output. If it runs at the requested point, Option C would be output. If it runs right at the end of the main() method, Option D would be output.(which is wrong) Option A is the correct answer because play is definitely called twice. Note that you are unlikely to see all these scenarios if you run this code because we have not used enough memory for garbage collection to be worth running. However, you still need to be able to answer what could happen regardless of it being unlikely."
As per chapter 2 - Q.17 explanation on p.434 "The finalize() method may not be called, such as if your program crashes. However, it is guaranteed to be called no more than once."So, There are not two following possible outputs of this code
Welcome to CodeRanch! The book is correct, but this question is tricky so I'm glad you asked!
Note that there are two Toy instances in this example. The finalize() method is called an an object instance (not on a class level.) This means, it is guaranteed to be called no more than once *per instance*. Since we have two instances in the code, clean may be printed zero, one or two times.
I'm preparing to OCA and this question is unclear for me. It is about answer C, when it is possible to happen. Even if garbage collector run on demand after call System.gc(), then it may happen before second object is created. But the first object is still referenced by car variable so it is not suitable for garbage collection so finalize() will not be called. Only right after main method both variables are out of scope and would be both collected by GC.
Oh! You are right. There should be a car= null; in there!
I think C would be right without it (because GC doesn't have to get all the garbage, but not sure. And that's definitely not something you need to know for the exam. The null assignment makes the question what we were trying to ask.