ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Resource {
    String name;
    Resource(String n) { name = n; }
    @Override
    protected void finalize() { System.out.print("finalizing:" + name + " "); }
}
Which statement about overriding finalize() here is correct, in modern Java (9+)?
  1. A. It compiles and runs exactly once per garbage collection cycle, synchronously
  2. B. It compiles but is strongly discouraged and deprecated: finalize() timing is unpredictable and it may never run before the JVM exits
  3. C. It compiles and is guaranteed to run immediately when the object goes out of scope
  4. D. It fails to compile: finalize() cannot be overridden

Correct answer: B. It compiles but is strongly discouraged and deprecated: finalize() timing is unpredictable and it may never run before the JVM exits

Overriding Object.finalize() is legal syntax, but it has been deprecated since Java 9 specifically because its execution is neither guaranteed nor timely — the garbage collector may run it late, multiple times in edge cases historically, or not at all before JVM shutdown; try-with-resources/AutoCloseable is the recommended replacement.

More OOP with C++ and Java questions

Exams that ask this topic