Final vs. Finally vs. Finalize

The terms final, finally, and finalize() in Java are distinct concepts often confused by beginners due to their similar names. However, each serves a very different purpose in the language. Let’s break down their roles:

Final Keyword

The final keyword is a modifier in Java that can be applied to classes, methods, and variables. It has the following roles:

Final Class: When a class is declared as final, it cannot be extended (inherited) by other classes.

public final class ImmutableClass {
    // Class code
}

Final Method: A method declared as final cannot be overridden by any subclasses.

public class ParentClass {
    public final void display() {
        System.out.println("This cannot be overridden");
    }
}

Final Variable: A variable declared as final cannot have its value changed once assigned. It acts as a constant.

final int MAX_ATTEMPTS = 3;

Finally Block

The finally block is a code block associated with a try-catch statement. It is used to execute code regardless of whether an exception occurs or not. Typically, it is used for resource cleanup (like closing files, database connections, etc.). The finally block always executes, except when the program exits due to a fatal error or a call to System.exit().

Example:

try {
    // Risky code that might throw an exception
} catch (Exception e) {
    // Exception handling code
} finally {
    // Code that will execute no matter what (cleanup code)
}

Finalize Method

The finalize() method is a method in Java’s Object class. It was traditionally used to perform cleanup actions before an object is removed from memory (i.e., before garbage collection). Java’s garbage collector calls this method on objects that are eligible for garbage collection.

Example:

@Override
protected void finalize() throws Throwable {
    try {
        // Cleanup code
    } finally {
        super.finalize();
    }
}

However, relying on finalize() is discouraged as it is not guaranteed to be called in a timely manner or even at all. Instead, you should use the try-with-resources statement or manually close resources in a finally block. Java 9 deprecated the finalize() method due to its unreliability and unpredictable behavior.

Key Differences:

  • Final: Used to declare constants, prevent method overriding, and inheritance of classes.
  • Finally: A block used for code that must be executed irrespective of exceptions (resource cleanup).
  • Finalize(): A method to be called before the garbage collector destroys an object (not recommended for use).