Understanding the Difference Between final, finally, and finalize in Java

A Complete Guide to final, finally, and finalize in Java with Examples

Understanding the Difference Between final, finally, and finalize in Java

Java provides three distinct terms—final, finally, and finalize—each serving difference purposes. While they may sound similar, their usage varies significantly in Java programming. In this article, we'll break down their functionalities, use cases, and best practices to help you understand them better

Final Keyword

The final keyword in Java is used to apply restrictions on classes, methods, and variables.

Usage of final:

At the Class Level : If a class is declared as final, it cannot be extended by any subclass.

final class ImmutableClass { // Class code
}
// This will cause an error
class ChildClass extends ImmutableClass {}

At the Variable Level: If a variable is declared as final, its value cannot be changed once initialized

class Example {
    final int MAX_VALUE = 100;
    void modifyValue() {
        // MAX_VALUE = 200; // This will cause a compilation error
    }
}

At the Method Level: A method declared as final cannot be overridden by subclasses.

class Parent {
    final void show() {
        System.out.println("Final method");    }
}
class Child extends Parent {
    // void show() { } // This will cause a compilation error
}

Use Cases of final:

  1. Creating Immutable Classes – Declaring a class as final prevents modification of its behavior through inheritance.

  2. Defining Constants – Variables that should not change their values (e.g., static final constants) are marked as final

Finally Block

The finally block in Java is used for exception handling and is always executed after the try or catch block, regardless of whether an exception occurs or not

Usage of finally:

Example: Using finally with Exception Handling

class FinallyExample {
    public static void main(String[] args) {
        try {
            int data = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("This block will always execute");
        }
    }
}

Output: Exception caught: java.lang.ArithmeticException: / by zero This block will always execute

Use Cases of finally:

  1. Resource Clean-up – Closing file streams, database connections, or network sockets to avoid memory leaks.

  2. Releasing Locks – Ensuring that a lock is released even if an exception occurs.

Finalize() Method

The finalize() method in Java is called by the Garbage Collector before an object is removed from memory. It allows an object to perform cleanup operations before being collected.

Usage of finalize():

Example: Using finalize() for Cleanup

class FinalizeExample {
    protected void finalize() {
        System.out.println("Finalize method called before garbage collection");
    }
    public static void main(String[] args) {
        FinalizeExample obj = new FinalizeExample();
        obj = null;
        System.gc(); // Suggesting JVM to run garbage collector
    }
}

Use Cases of finalize():

  1. Releasing System Resources – Helps in cleanup activities like closing database connections.

  2. Logging Object Removal – Useful for tracking object destruction during debugging

Key Dierences Between final, finally, and finalize

Featurefinal Keywordfinally Blockfinalize()
TypeKeywordBlockMethod
PurposeRestricts inheritance, overriding, and reassignmentEnsures code execution after try/catchCalled before garbage collection
Used WithClasses, Methods, VariablesException HandlingObject Cleanup
Execution TimingCompile-time restrictionRuntime, always executes after try/catchBefore object is garbage collected

Have any questions or need help with backend interview prep? Drop a comment below, and let's discuss! Also, don’t forget to subscribe for exclusive interview insights delivered to your inbox!

"Enjoyed this article? Get more backend interview tips, DSA guides, and system design insights straight to your inbox!"

Follow us on LinkedIn for exclusive content → InterviewInsights