Read Also: Exception Handling Interview Questions and Answers
1. Final Keyword
In Java, the final keyword can be used in three ways:1. Variable can be declared final
2. The method can be declared final
3. The class can be declared final
Each of the above has a different effect on the java program. Let's understand each of them in detail below.
1.1 Final Variable:
When a variable, field or parameter is declared as final, its value can never be changed throughout the execution of the java program.
Note: The variable becomes a constant once it is declared as final.
If you try to change the value of the final variable, then it will result in a compilation error.
public class JavaHungry { public static void main(String args[]) {
//Normal variable var1
int var1 = 10; /*Declaring final variable var2, It becomes a constant which has a value 100 and can not be modified further in the program*/ final int var2 = 100; System.out.println(var2);
//Modify normal variable var1
var1 = 1000; // No Compile time Error
/*Trying to modify final variable var2 value */ var2 = 10000; // Compile time error } }
Output:
JavaHungry.java:28: error: cannot assign a value to final variable var2
var2 = 10000; // Compile time error
^
1 error
In case a variable is declared as final and no value is assigned to the variable then it is called a blank final variable or uninitialized final variable. These variables can only be initialized through a constructor.
public class JavaHungry { //Declaring blank final variable final int var1; //Declaring and Initializing final variable final int var2 = 123; JavaHungry() { /*Initializing blank final variable through Constructor */ var1 = 456; // No Compiler error // Modifying final variable value var2 = 456; // Compiler error } }
Output:
JavaHungry.java:14: error: cannot assign a value to final variable var2
var2 = 456; // Compiler error
^
1 error
From the above example how a final keyword affects the variable in a program is understood. Let's see how the final keyword affects the method below.
1.2 Final Method
When a method is declared as final in a base class or parent class, then the method cannot be overridden by its child classes throughout the execution of the program.
Note: Parent class final method(s) cannot be overridden by any child class.
The result will be compilation error if child class overrides the method declared as final in the parent class as shown below.
class ParentClass { final void sampleMethod1 () { System.out.println("This method is Final so cannot be overridden"); } void sampleMethod2() { System.out.println("This method can be overridden as it is a normal method"); } } public class ChildClass extends ParentClass { void sampleMethod1() { // Compile Time Error } void sampleMethod2() { System.out.println("This method overrides the parent class method"); } public static void main(String args[]) { ParentClass obj = new ChildClass(); obj.sampleMethod1(); obj.sampleMethod2(); } }
Output:
ChildClass.java:17: error: sampleMethod1() in ChildClass cannot override sampleMethod1() in ParentClass
void sampleMethod1() {
^
overridden method is final
1 error
As of now, we have seen how the final keyword affects the method and variable. Let’s see how it affects the class.
1.3 Final Class
Whenever a class is declared as final, then the class cannot be inherited by any child class or subclass. When a class is declared as final then all its methods including the private methods behave as if they are final, since it is impossible to override them.
Note: Class declared as final can not be inherited by any child class or subclass.
The result will be compilation error if child class try to inherit the parent class declared as final.
// final class final class ParentClass { //parent class body } class ChildClass extends ParentClass {//compilation error //child class body }
Output:
ChildClass.java:8: error: cannot inherit from final ParentClass
class ChildClass extends ParentClass {//compilation error
^
1 error
2. Finally Block
Finally block is used after the try/catch block as an optional block while performing exception handling. In java, finally block is used to perform operations such as resource cleanup or free up the memory space. Using finally and performing the cleanup operation is considered as a good coding practice. Hence irrespective of the fact, whether an exception is handled or not, finally gets executed.
Note: When a try block executes the statement System.exit(0) before the exception is thrown by it. Then finally block will not get executed.
Except for the above scenario, finally block will always get executed in the java program. You can find the code example below.
public class JavaHungry { public static void main(String args[]) { try { System.out.println("You are in try block"); System.exit(0); throw new Exception(); } catch (Exception e) { System.out.println("Thrown exception gets caught in catch block"); } finally { System.out.println("You are in finally block"); } } }
Output:
You are in try block
3. Finalize method
The finalize method is defined within the Object class and is a protected, non-static method available for all objects in the java. Before an object is destroyed, the finalize method gets called by the garbage collector when it determines that there are no other references of the object present in the java virtual machine (JVM). The sole purpose of this method being called by the garbage collector, just before an object gets destructed is because the object may have to close an opened database connection, free up used resources in memory and so on. These tasks must be handled well in order to maintain the performance of the program.
Note: The finalize method will not be invoked by the JVM more than once for any given object.
public class JavaHungry { public void finalize() throws Throwable { System.out.println("Finalize method is called"); } public static void main(String[] args) { JavaHungry test = new JavaHungry(); /* There are no more references to the object test in jvm */ test = null; //Calling garbage collector System.gc(); } }
Output:
Finalize method is called
Recap : Difference between final, finally and finalize in Java
final | finally | finalize | |
---|---|---|---|
Definition | final is a keyword which can be used with variables, methods and classes | finally is a block which can be used with try/catch block in exception handling | finalize is a method that is called just before the object is garbage collected. |
Function | final variable in Java is a constant. Once assigned its value can’t be changed. 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 of the object before it is destroyed by the garbage collector |
That's all for today. Please mention in comments in case you have any questions related to the difference between final, finally and finalize in java.