Difference between final, finally, and finalize in Java

1. Introduction

In Java, final, finally, and finalize are three concepts that often cause confusion due to their similar names. However, they serve entirely different purposes. 

final is a keyword used to define an entity that cannot be modified after it's initialized. 

finally is a block used in exception handling that executes code regardless of whether an exception is thrown. 

finalize is a method from the Object class, which the garbage collector calls before object memory is reclaimed.

2. Key Points

1. final can be used to define variables, methods, and classes that cannot be changed, overridden, or inherited.

2. finally is a block that complements the try-catch blocks in exception handling.

3. finalize is a method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

4. final is a keyword, finally is a block, and finalize is a method.

3. Differences

final finally finalize
Used to declare constants, prevent inheritance, or prevent method overriding. Used in exception handling to define a block of code that follows a try-catch block and executes regardless of whether an exception was caught. Used as a method that the garbage collector calls to clean up the system resources before an object is removed from the memory.
It can be used with variables to make them unchangeable once initialized. Ensures that the code block within it executes even if there is an exception or a return statement in the try or catch blocks. It's an Object class method that can be overridden to include cleanup code, such as closing files or releasing resources.
It can be applied to classes to prevent them from being subclassed. There is always zero or one finally block following try-catch blocks. Java's garbage collector does not guarantee when or if the finalize method will be called.
final variables can be initialized only once, either at the time of declaration or within the constructor of the class. Often used for cleanup activities, like closing file streams or database connections. The finalize method is executed only once by the garbage collector before object deallocation.

4. Example

// Example of final
final int NUMBER = 42;

// Example of finally
try {
    // Code that may throw an exception
    int division = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Exception caught!");
} finally {
    System.out.println("This will always be printed, even if there is an exception.");
}

// Example of finalize
public class SampleObject {
    // The finalize method
    protected void finalize() throws Throwable {
        try {
            // Cleanup code or resource release logic
            System.out.println("Finalize method called.");
        } finally {
            super.finalize();
        }
    }
}

// Let's assume SampleObject gets used and is now ready to be garbage collected.

Output:

Exception caught!
This will always be printed, even if there is an exception.
// Finalize method output may not show up in a predictable manner as it depends on the garbage collector.

Explanation:

1. final keyword is shown being used with a variable, making the variable's value unchangeable after initialization.

2. finally block is shown in context with try-catch, to ensure that some code is executed after try-catch, irrespective of an exception.

3. finalize method is shown inside a class definition, showcasing how it can be used to execute cleanup code before an object is garbage collected.

5. When to use?

Use final when you want to create a constant variable, prevent method overriding, or prevent inheritance.

Use finally when you have critical code that must be executed regardless of an exception occurring, such as closing resources.

Use finalize to perform clean up of resources before an object is garbage collected, although it's generally recommended to use other resource management techniques,

Comments