by BehindJava

What is the difference between final, finally, finalize in Java

Home » java » What is the difference between final, finally, finalize in Java

In this tutorial, we are going to learn about the major differences between final, finally, finalize in Java with examples.

Final

Final is a modifier applicable for classes, methods and variables. When a class is declared as final then we cant extend that class and we cannot the create child class.
If a method is declared as final then we cannot override that method in the child class.
If a variable is declared as final then it behaves as a constant and we cannot perform any re-assignment for that variable.

Sample Code Snippet:

class FinalVariable
{
   public static void main(String[] args)
   {
      final int hours=24;
      System.out.println("Hours in 6 days = " + hours * 6);
   }
}

Output:

Hours in 6 days = 144

Finally

Finally is a block that is associated with try & catch block. usually try block is meant for handling the code that causes the exception followed by catch that handles the exception, followed by the finally block for cleanup activities such as closing database or network connections etc.

syntax:

try
{
    //risky code 
}
catch(Exception e)
{
    //handling exception
}
finally
{
    //cleanup code
    con.close();
}

Finalize()

finalize() is a method which is always invoked by garbage collector just before destroying an object to perform cleanup activities such as closing a database or network connections.

Example:
Lets say, we have an object ready for Garbage collection which means the object doesn’t have any references.
Before destroying the object the garbage collector calls the finalize method to close any existing the database or network connections.

Note:

You may wonder that why both finally and finalize are meant for cleanup activities? finally is meant for cleaning up the resources or objects that are used in the try & catch blocks where as finalize is meant for clean up activities related to object.