Saturday, April 5, 2014

final, finally and finalize in Java


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


The keyword “final” means constant. A final variable is a constant variable. A final method cannot be overridden. A final class cannot be extended.
The keyword “finally” is for catching exceptions. When all the specified type of exceptions have been caught, the finally block will be executed to handle the rest unspecified exceptions.
The keyword “finalize” is for user-defined garbage collection. You can write your own destructor in the finalize block.
  • Final
    When applied to a variable (primitive): The value of the variable cannot change.
    When applied to a variable (reference): The reference variable cannot point to any other object on the heap.
    When applied to a method: The method cannot be overridden.
    When applied to a class: The class cannot be subclassed.
  • Finally
    There is an optional finally block after the try block or after the catch block. Statements in the finally block will always be executed (except if JVM exits from the try block). The finally block is used to write the clean up code.
  • Finalize
    This is the method that the JVM runs before running the garbage collector.

protected void finalize()
// finalization code here



Post a Comment