final, finally and finalize in Java

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

My initial thoughts:
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.

Solution:

  • 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
    }
    
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: