Final VS Finally VS Finalize In Java Details

Final VS Finally VS Finalize In Java: In this article, we will discuss the difference between final, finally and finalize in detail with an example. This is, one of the top interview questions for Java fresher’s and at the junior level to check the knowledge of core Java concepts

First of all, final & finally & finalize is used in different scenarios and also they aren’t similar in any context like

  • final is a keyword used for restricting further alteration in inheritance
  • Finally is a block & it is associated with the try-catch block in exception handling for clean-up activity
  • finalize() is a method associated with the garbage collector to de-allocate resources associated with the Object

Let us discuss each one in detail for example

Final Keyword

  • final is keyword or modifier
  • applicable only for variable, method & classes
  • a variable declared as final can’t be changed or re-assigned once it is initialized
  • a method declared as final can’t be overridden in the subclass (inheriting class or extending class)
  • a class declared as final can’t be extended i.e.; inherited further (or subclass)
  • Read more about the final keyword or modifier

Variable declared as final can’t be re-assigned

Compile-time error: The final field FinalKeyword.count cannot be assigned

A method declared as final can’t be overridden

Compile-time error: Cannot override the final method from ParentClass

A class declared as final can’t be extended or inherited or sub-classed

Compile-time error: The type ChildClass cannot subclass the final class ParentClass

Finally Block

  • finally is a block associated with a try-catch block in exception handling concept
  • It is used to provide clean-up code for releasing resources used in try block like a database connection or IO resources or network resources
  • The beauty of finally block is that it is always gets executed, irrespective of whether an exception is thrown or NOT and whether an exception is handled or NOT
  • Read more about finally block

FinallyBlockExample.java

package in.bench.resources.exception.handling;
public class FinallyBlockExample {
    public static void main(String[] args) {
        try {
            // code which might raise exception
 
            int result = 19/0;
            System.out.println("Result of division : " + result);
        }
        catch(ArithmeticException aex) {
 
            // corresponding handling code, if any exception from try block
 
            System.out.println(aex.toString());
        }
        finally {
 
            // finally block always gets executed for code clean-up activities
 
            System.out.println("finally block always gets executed");
            // rest of the code clean-up
        }
    }
}

Finalize() Method

  • finalize() is a method is associated with the garbage collector
  • this method is invoked just before destroying an Object i.e.; to provide clean-up activities
  • After Garbage Collector invokes finalize() method, then immediately it destroys an Object
  • A programmer doesn’t have any control over the invocation of finalize() method because it is internally invoked by garbage collector for null objects (although, we can make Object as null by assigning to null reference)

Method signature:

protected void finalize() throws Throwable;

FinalizeMethodExample.java

package in.bench.resources.exception.handling;
public class FinalizeMethodExample {
    protected void finalize() throws Throwable {
        System.out.println("finalize() method invoked to clean-up Object resources");
    }
    public static void main(String[] args) {
        // create Object of type FinalizeMethodExample
        FinalizeMethodExample fme = new FinalizeMethodExample();
        // explicitly making null
        fme = null;
    }
}

Explanation:

  • When the above program is executed, it doesn’t print any sysout statement from finalize() method
  • Because it is the garbage collector’s duty to invoke the finalize() method just before destroying the Object
  • And hence programmer can’t make sure that it is compulsorily invoked although we can make any Object as null explicitly

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment