Describe how the Java garbage collector uses finalization to allow objects to clean up after themselves.
Java Garbage Collection and Finalization
Finalization
The garbage collector invokes an object's finalize() method to allow the object to perform any completion processing, such as closing an open socket or disposing of a window, before the object is destroyed.
When an object's finalize() method is invoked, it is possible for the object to become reachable again by assigning itself to a reachable program variable. Because of this possibility, the garbage collector does not immediately destroy an object after its finalize() method has completed. Instead, it waits until the next time that it has identified the object as unreachable.
Java Virtual Machine
Which option is true about compiling and running the following code?
public class Test extends SuperTest {
String s="abc";
public static void main(String[] args) {
Test t=new Test(); //2
t.finalize(); //3
}
}
Please select one option:
Code will compile only if line 1 is removed.
Code will compile only if line 3 is removed.
Prints "SuperTest".
Prints "SuperTest" only if garbage collector runs.
Causes an exception to be thrown at runtime.
None of the above.
Answer: a Explanation:
Here the code will compile only if line 1 is removed. The super.finalize() method call invokes the finalize() method defined in the Object class. The finalize() method in the Object class throws Throwable, and since it is not handled at line 1, the code will not compile. There is no error in line 3. It is valid to invoke the finalize() method directly. If line 1 is removed, the code will compile and print "SuperTest".