top of page
jayabb258

Difference between final, finally and finalize in java

Definition:


Final: Final is the keyword and access modifier which is used to apply restrictions on a class, method or variable.

Finally: Finally is the block in Java exception handling to execute the important code whether the exception occurs or not.

Finalize: Finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.


Final:


The keyword final when used with different Java entities:


Variable - The final keyword when used with a variable tells the compiler that the variable with which the keyword is associated is a constant which means the value for the variable cannot be changed.


class A {

public static void main(String[] args)

{

// Non final variable

int a = 5;


// final variable

final int b = 6;


// modifying the non final variable : Allowed

a++;


// modifying the final variable :

// Immediately gives Compile Time error.

b++;

}

}


Method – When used with a method tells the compiler that if any class inherits or extends the class in which there is a method which is declared as final, then the method cannot be overridden in the child class.


class QQ {

final void rr() {}

public static void main(String[] args)

{

}

}


class MM extends QQ {


// Here we get compile time error

// since can't extend rr since it is final.

void rr() {}

}



Class – When used with a class tells the compiler that the class that is declared as final cannot be extended which means no class can inherit any property from that class.  


final class RR {

public static void main(String[] args)

{

int a = 10;

}

}

// here gets Compile time error that

// we can't extend RR as it is final.

class KK extends RR {

// more code here with main method

}

 

·      Final is a keyword.

·      It can also be used as an access modifier. It is used to apply user restrictions on classes, methods and variables.

·      It can’t be inherited or overridden. This is useful to keep the implementation of a method unchanged in the inheritance hierarchy.

·      It ensures that the semantic behavior of the method stays consistent across different subclasses.

·      Executed when it is invoked by the compiler.

·      Final methods can’t be inherited by any class.

·      It is needed to initialize the final variable when it is being declared.

·      It effectively makes the variable a constant. This is useful for defining values that should remain constant throughout the execution of a program, like final int MAX_SIZE = 100;

·      It’s value, once declared, can’t be changed or re-initialized.

·      If a class is declared as final as by default all of the methods present in that class are automatically final, but variables are not. 

·      It is useful when creating immutable classes like String or utility classes that should not be altered through inheritance.


Finally:


The finally block is used in exception handling. It is a block of code that follows a try block and is executed after the try and catch blocks, regardless of whether an exception was thrown or not. This is useful for cleanup activities.


try{

        // Code that may throw an exception

} catch (Exception e) {

        // Handle exception

} finally {

        // This block will always execute

       System.out.println(“This will always execute.”);

}

 

·      Finally is a block. An optional block which is used for the Exception Handling.

·      It is used to place important code in this block.

·      Generally executes right after the execution of try-catch block.

·      It gets executed irrespective of whether the exception is handled or not.

·      It is typically used for cleanup activities, such as closing file streams, releasing resources, or other necessary housekeeping tasks that should occur regardless of whether an error occurred or not.

·      The only scenarios in which the finally block will not execute are if the JVM exits during the try or catch block, or if the thread executing the try or catch block is interrupted or killed.

·      Finally block is crucial for preventing resource leaks. For instance, if try block opens a file for reading and an exception occurs, without a finally to close the file, it would remain open.

·      It ensures that important cleanup tasks are performed even if an unexpected exception disrupts the normal flow of code execution.


Finalize():


The finalize() method is a protected method of the java.lang.Object class. Finalize is something we wouldn’t normally use in our code. It is called by the garbage collector before the object is reclaimed, allowing for cleanup before the object is destroyed.

Java does garbage collection automatically and you want to do some operation whenever an object gets destroyed or memory is freed up. You can use garbage collector method finalize to override it with some code of those operations to perform whenever an object is destroyed.

 


@Override

Protected void finalize() throws Throwable {

           try {

               // Cleanup code

           } finally {

                   Super.finalize(); //Always call the superclass’s finalize method

            }

 }

 

·      Finalize is a method.

·      Declared in the Object class protected void finalize() throws Throwable.

·      Protected non-static method that is defined in the Object class.

·      Used with objects which are no longer in use.

·      Need not call the finalize method explicitly in the code, it is invoked automatically.

·      It is used to perform clean up processing right before the object is collected by garbage collector.

·      There is no guarantee when, or even if, the finalize method will be invoked. The timing depends on the garbage collector, which operates asynchronously.

·      Executes just before an object is destroyed.


How to exit or terminate execution from finally block. There are 2 ways to do the forceful exit:


1.  If finally block is directly inside main() method then simply use a return statement to terminate the program. As soon as return is executed inside main, it will terminate the program.

2.  If finally block is inside some other method which has been called from either main or from any other method then just a return statement would not help as the return statement would only exit out of the method in which the finally block is present. To actually terminate the program System.exit(0) will actually kill the process or program.



Note: 


  • Finalize has been deprecated in Java 9 and removed in later versions.

  • Java offers better alternatives for managing resources, such as try-with-resources and the AutoCloseable interface, which provide a more predictable way of releasing resources.

 


Conclusion:


While final is used to create constants and prevent method overriding or class inheritance, finally is a block that executes after try-catch for guaranteed execution, typically for cleanup. On the other hand, finalize is a method called before an object's garbage collection, used for final resource release tasks.



“Your positive action combined with positive thinking results in Success”.

25 views

Recent Posts

See All
bottom of page