Discuss the difference between finalize() and finally. Under what circumstances might finalize() not get called in a Java application?

finalize() and finally serve completely different purposes in Java. The finalize() method is related to garbage collection and object cleanup, whereas the finally block is part of exception handling and is used to execute critical cleanup code regardless of whether an exception occurs.

Key Points: • finalize() is a method of the Object class, while finally is a block used with try-catch statements. • finalize() is invoked by the Garbage Collector before reclaiming an object's memory, whereas finally executes after the try-catch block completes. • The execution of finalize() is not guaranteed, but finally is executed in almost all normal circumstances. • Since Java 9, finalize() has been deprecated because of its unpredictability and performance issues. • Modern Java applications use try-with-resources or explicit resource cleanup instead of finalize().

Difference Between finalize() and finally:

finalize(): • Method in Object class • Related to Garbage Collection • Execution is not guaranteed • Called before object reclamation • Deprecated in modern Java

finally: • Block used in exception handling • Related to resource cleanup • Executes regardless of exceptions • Runs after try/catch execution • Widely used in Java applications

Example: A database connection should be closed in a finally block because its execution is reliable. Using finalize() for closing resources is not recommended because the Garbage Collector may not run immediately.

Code Example:

public class Demo {

    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize() called");
    }

    public static void main(String[] args) {

        try {
            System.out.println("Inside try");
        } finally {
            System.out.println("Inside finally");
        }
    }
}

Interview Tip: A concise interview answer is:

"finalize() is a method associated with garbage collection and may be called before an object is removed from memory, whereas finally is an exception-handling block that executes after a try-catch statement. finalize() is not guaranteed to run and may never be called if the Garbage Collector does not execute before the JVM shuts down, which is why it is deprecated and generally avoided in modern Java applications."