Saturday, April 5, 2014

final, finally and finalize in Java

Problem

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

Solution

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
}

References
http://tianrunhe.wordpress.com/2012/04/15/final-finally-and-finalize-in-java/

0 comments:

Post a Comment