If you have any prior experience of Java Interviews, then you might have noticed that the interviewers tend to ask tricky questions usually picked up from the basic concepts. One such question which is mostly asked is to differentiate between final, finally and finalize in Java. Through the medium of this article, I will be drawing a clear line between final, finally and finalize in Java which will help you in gaining better insights.

In this article I will be covering the following topics:

So, let’s get started with the very first keyword among final, finally and finalize in Java.

Final Keyword

In Java, final is a keyword which can also be used as an access modifier. In other words, the final keyword is used to restrict a user’s access. It can be used in various contexts like:

  1. Final Variable
  2. Final Method
  3. Final Class

With each of these, the final keyword has a different effect. Let’s now see how it affects each of them one by one.

1. Final Variable

Whenever the final keyword in Java is used with a variable, field or parameter it means that once the reference is passed on or the instantiation is done then its value cannot be changed throughout the execution of the program. In case a variable without any value has been declared as final then it is known as blank/uninitialized final variable and can be initialized only through a constructor.

Let’s now see an example.

public class A {
int var1 = 123;
//declaring final variables
final int var2 = 345;
final int var3;

//Trying to initialize a blank final variable
var = 555; //Error

A (){
var1 = 111; //No Error
var2 = 333; //Compilation Error

//Initializing a blank final variable
var3 = 444; //No Error
}

//passing final parameters
void avg(int param1, final int param2){
param1 = 2345; //No Error
param2 = 1223; //Compilation Error
}

//declaring final fields
void show(){
final int fieldVal = 300000;
fieldVal = 400000; //Error
}

}

So, this was all about how the final keyword affects a variable, let’s now see how a method is affected by it.

2. Final Method

In Java, whenever a method is declared as final it cannot be overridden by any child class throughout the execution of the program.

Let’s see an example.


//FINAL METHOD
class A {
final void method_abc(){
System.out.println("This is a Final method and cannot be overridden");
}

void method_xyz(){
System.out.println("This is a normal method and can be overridden");
}
}

class B extends A {
void method_abc{
//Compile Time Error
}

void method_xyz(){
System.out.println("This is an overridden method in class B");
}

}

Till now you have already seen the results of declaring a variable and a method final, lets now move further and see what happens when a class is declared as final in Java.

3. Final Class

In Java, whenever a class is declared as final, it cannot be inherited by any subclass. This is because, once a class is declared as final, all the data members and methods contained within the class will be implicitly declared as final. Also, once a class is declared as final it can no longer be declared as abstract. In other words, a class can be either of the two, final or abstract.

Let’s see an example.


//FINAL CLASS
final class A {
//class body
}

class B extends A{ //Compilation Error
//class body
}

I hope by now, you have clearly understood the working of the final keyword. So, let’s now move ahead with this article on final, finally and finalize in Java to find out the role of finally keyword.

Finally Block

In Java, finally is an optional block which is used for the Exception Handling. It is generally preceded by a try-catch block. Finally block is used to execute an important code such as resource cleanup or free the memory usage, etc. A finally block will be executed irrespective of the fact whether an exception is handled or not. Thus, wrapping the cleanup codes in a finally block is considered as a good practice. You can also use it with a try block without needing any catch block along with it.

Let’s now see an example of the same.

class A {
public static void main(String args[]) {
try {
System.out.println("Try Block");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch Block");
} finally {
System.out.println("Finally Block");
}
}
}

Till now, I have already discussed the final and finally keywords in Java. Let’s  now throw some light on the last keyword among the three that is, finalize keyword in Java.

Finalize Method

Finalize is a protected non-static method that is defined in the Object class and thus is available for any and all the objects in Java. This method is called by the garbage collector before an object is completely destroyed. As sometimes, an object might have to complete some important task like closing an open connection, freeing up a resource, etc before it gets destroyed. If these tasks are not done, it might decrease the efficiency of the program. Thus, the garbage collector calls it for the objects that aren’t referenced anymore and have been marked for garbage collection.

This method is declared as protected to restrict its use from outside the class. But you can override it from within the class to define its properties at the time of garbage collection.

Let’s see an example of the same.


public class A {
public void finalize() throws Throwable{
System.out.println("Object is destroyed by the Garbage Collector");
}
public static void main(String[] args) {

Edureka test = new Edureka();
test = null;
System.gc();
}
}

With this, we come to an end of this article on final, finally and finalize in Java. To conclude this, I have added a comparison between all the three keywords which will help you in fetching the major differences at a glance.

Comparison Table – Final vs Finally vs Finalize Keywords in Java

Factor Final Finally Finalize
Definition
Final is a keyword and is used as access modifier in Java Finally is a block in Java used for Exception Handling Finalize is a method in Java used for Garbage Collection
Application
Final in Java is used with variables, methods, and classes to set access permissions Finally block is used along with a try and catch block Finalize method in Java is used with objects which are no longer in use
Function
Final variable in Java is a constant whose value can’t be changed once assigned.

Final method in Java can’t be overridden by its child classes.

Final class in Java can’t be inherited by any child class.

Finally block in Java helps in cleaning up the resources that have been used in the try block Finalize method helps in clean up activities for the object before it is destroyed by the garbage collector
Execution
It is executed when it is invoked by the compiler Executes right after the execution of try-catch block It executes just before an object is destroyed

I hope through this Final, Finally and Finalize in Java, I was able to clear the concepts and helped you in adding value to your knowledge.

If you found this article on “Final, Finally and Finalize in Java” relevant, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 
Got a question for us? Please mention it in the comments section of this Final, Finally and Finalize in Java and we will get back to you.