What is the Difference Between final finally and finalize in Java?

🆚 Go to Comparative Table 🆚

The keywords final, finally, and finalize in Java serve different purposes and have distinct functionalities:

  1. final:
  • Used to declare a variable, method, or class as unchangeable.
  • When applied to a variable, its value cannot be changed once initialized.
  • When applied to a method, it cannot be overridden by any subclass.
  1. finally:
  • A block used in Java to ensure that a section of code is always executed, even if an exception is thrown.
  • It is used in association with a try/catch block and guarantees that the code within the finally block will be executed, even if the try block has a return statement.
  1. finalize:
  • A method in Java used to perform cleanup processing on an object before it is garbage collected.
  • It is called just before the object is reclaimed by the garbage collector, and it is the last chance for any object to perform cleanup activities.
  • However, there is no guarantee that the finalize method will be called by the garbage collector, and an object may wait indefinitely after becoming eligible for garbage collection.

In summary, the final keyword is used to create constants or non-modifiable elements, the finally block is used in exception handling to execute code regardless of whether an exception is thrown, and the finalize method is called to perform cleanup operations on an object before it is garbage collected.

Comparative Table: final finally vs finalize in Java

Here is a table comparing the differences between final, finally, and finalize in Java:

Feature Description Usage
final Restricts the modification of a variable, method, or class final variable, method, or class
finally Ensures a section of code is always executed, even if an exception is thrown After a try or catch block
finalize Performs cleanup processing on an object before it is garbage collected Method in Java used for cleanup operations on an object
  • final:

  • Used with variables, methods, and classes to restrict modification.

  • Final variable: constant value that cannot be changed once assigned.

  • Final method: cannot be overridden by child classes.

  • Final class: cannot be inherited by child classes.

  • Execution: Invoked by the compiler.

  • finally:

  • Used to ensure a section of code is always executed, even if an exception is thrown.

  • Executed after the try-catch block.

  • Helps in cleaning up resources used in the try block.

  • finalize:

  • Used to perform cleanup operations on an object before it is garbage collected.

  • Executed just before an object is destroyed by the garbage collector.

  • Not guaranteed to be called by the garbage collector.