A2oz

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

Published in Java Keywords 3 mins read

In Java, final, finally, and finalize are distinct keywords with completely different functionalities. Let's break down their differences:

Final

  • Purpose: The final keyword is used to declare a variable, method, or class as immutable. This means that the value of a final variable cannot be changed after it's initialized, and a final method cannot be overridden by subclasses.
  • Usage:
    • Variables: When a variable is declared final, its value cannot be changed after initialization.
    • Methods: A final method cannot be overridden by subclasses.
    • Classes: A final class cannot be extended (subclassed).
  • Example:
final int MAX_VALUE = 100; // Cannot be changed

class MyFinalClass {
    final void myMethod() {
        // This method cannot be overridden
    }
}

Finally

  • Purpose: The finally block is used to specify code that should be executed regardless of whether an exception is thrown or not within a try block.
  • Usage: It's always used in conjunction with a try block and is placed after the catch block (if any).
  • Example:
try {
    // Code that might throw an exception
} catch (Exception e) {
    // Handle the exception
} finally {
    // This code will always execute, even if an exception occurs
    System.out.println("This is the finally block.");
}

Finalize

  • Purpose: The finalize() method is a special method that is called by the garbage collector before an object is destroyed. It allows an object to perform some cleanup operations before being garbage collected.
  • Usage: This method is rarely used in modern Java programming. The finalize() method has been deprecated in Java 9 and is not recommended for use.
  • Example:
class MyObject {
    protected void finalize() throws Throwable {
        // Perform cleanup operations
        System.out.println("Object is being finalized.");
    }
}

Key Differences:

Keyword Purpose Usage
final Makes variables, methods, or classes immutable Used to restrict modification or inheritance
finally Executes code regardless of exceptions Used in conjunction with try blocks
finalize Allows cleanup operations before garbage collection Deprecated in Java 9

Note: It's important to understand that the finalize() method is not a guaranteed mechanism for resource cleanup. The garbage collector might not call it at all or call it at an unexpected time. It's generally better to use try-with-resources blocks or other mechanisms for proper resource management.

Related Articles