Java Basics 6

Final, finally and finalize difference?

In Java, "final", "finally" and "finalize" are three related but distinct concepts:

  1. "final" is a keyword that can be used to indicate that a variable, method, or class cannot be overridden or re-assigned. A final variable can only be assigned once, and its value cannot be changed after it is assigned. A final method cannot be overridden by a subclass. A final class cannot be extended by a subclass.
  2. "finally" is a block of code that is used in conjunction with a try-catch block. The code in the finally block will always be executed, regardless of whether an exception was thrown or caught in the try block. The finally block is useful for cleaning up resources that were acquired in the try block.
  3. "finalize()" is a method that is used to perform cleanup tasks before an object is garbage collected. This method is called by the garbage collector just before it releases the memory used by the object. The finalize() method can be overridden in a class to perform custom cleanup tasks, but it is not guaranteed to be called by the garbage collector.

In summary, "final" is a keyword used to make classes, methods, or variables final, "finally" is a block of code that is always executed in a try-catch block, and "finalize()" is a method that can be overridden to perform cleanup tasks before an object is a garbage collected.