Sobes.tech
Junior

What is the difference between the keywords final, finally, and the finalize method in Java?

sobes.tech AI

Answer from AI

final - a keyword for declaring constants, prohibiting class inheritance or method overriding.

finally - a block of code in a try-catch-finally construct that always executes, regardless of whether an exception was thrown.

finalize - a protected method of the Object class, called by the garbage collector before destroying the object. It is unpredictable and not guaranteed to execute.

Example of usage:

public final class FinalExample { // final class

    private final int constantValue = 10; // final field

    public final void doSomething() { // final method
        // ...
    }

    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Throwing an exception
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed."); // This block always executes
        }

        FinalExample obj = new FinalExample();
        // obj = null; // Object becomes available for garbage collection

        // Garbage collector MAY call finalize
        // System.gc(); // Explicit call to garbage collector, but does not guarantee finalize execution
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Finalize method called for object: " + this);
        super.finalize();
    }
}

Summary:

Keyword / Method Purpose Usage
final Restriction: constants, inheritance, overriding Fields, methods, classes
finally Guaranteed execution of code Block in try-catch
finalize Resource cleanup before object deletion Method of class Object, overridden