Difference between Final , Finally and Finalize

This article will help you understand the difference between Final , Finally and Finalize Keyword in Java :

Final Keyword :

Final keyword is basically used for provide some restrictions which are elaborated in this article. This keyword can be applied with variables, methods and classes.

Final Variables : Variables declared as final are constants. The value can not be changed of a final variable once the same is initialized. If a final variable is declared but not initialized , these are called as Blank Final variables.

The value to a blank final variable can only be assigned in the constructor.

If the blank final variable is static then it can only be initialized in the static block.

class FinalTest{
final int limit=90;//final variable
void run(){
limit=400;
}
public static void main(String args[]){
FinalTest obj=new FinalTest();
obj.run();
}
}

Output : Compile Time Error

Final Method :Β Method declared as final cannot be overridden.

class FinalMethod{
final void run(){System.out.println(“running”);}
}

class FinalMethod1 extends FinalMethod{
void run(){System.out.println(“running safely with 100kmph”);}

public static void main(String args[]){
FinalMethod1 obj= new FinalMethod1();
obj.run();
}
}

Output : Compile Time Error

Final Class :Β 

Final class cannot be inherited.

final class A{}

class B extends A{
void run(){System.out.println(“running safely with 100kmph”);}

public static void main(String args[]){
B b= new B();
b.run();
}
}

Output : Compile Time Error

Note :Β Β Β final method is inherited but you cannot override it.

Finally Keyword :

The important code that needs to be executed either exception is occurred or not needs to be placed in the finally block.Β  E.g. the code like closing the connection,Β  nullify the array or any other variable should be placed in the finally block.

Finally block is placed after try or catch block.

Finalize Keyword :

Finalize is a method that is present in Object class. It is called by JVM to perform clean up processing just before object is garbage collected.

finally

Thanks for reading this article. I hope , you like it,

For any suggestions / feedback / question / clarification, Kindly post your comments in the below comment box.

Please subscribe our news letter and connect with social media accounts and don’t miss any articles.

Happy Reading!!!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply