Differentiate Between Final, Finally And Finalize In Java
Differentiation between final, finally and finalize
Let’s see the differences between final, finally and finalize, which are,
Final
Final is a keyword, which is used to apply restrictions on class, method and variable. If we declare any class as a final, the class can't be inherited. If we declare any method as a final, the method can't be overridden and if we declare any variable as a final, the variable value can't be changed and initialized only once in Java.
Let’s see an example of final, given below.
Code
- public class Employee {
- final int empId = 101; //final variable
- void work() {
- empId = 211; // Compile time error
- }
- public static void main(String args[]) {
- Employee obj = new Employee();
- obj.work();
- }
- }
In the example, shown above, we declare the final variable and initialize it at the time of the declaration. Hence, we cannot initialize it again or we cannot change its value. It will be constant.
Finally
Finally is a block, which is used to place the important code. It always executes whether an exception is handled or not. It must be followed by try or catch block. Finally, block allows us to run any cleanup-type statements, which we want to execute, no matter what happens in the protected code such as closing a file, closing connection etc.
Let’s see an example of final, given below.
Code
- package exceptionHandling;
- public class FinallyExample2 {
- public static void main(String args[]) {
- try {
- int num = 36 / 0;
- System.out.println(num);
- } catch (NullPointerException e) {
- System.out.println(e);
- } finally {
- System.out.println("finally block....");
- }
- System.out.println("Rest code...");
- }
- }
Output
In the above example, we can see that exception occurred and not handled but finally block is always executes whether exception is handled or not.
Finalize
Finalize is a method, which is used to perform clean up processing before an object is garbage collected, finalize() method calls at the runtime and we can write the system resources, which released code in finalize() method before getting garbage collected in Java.
Let’s see an example of finalize, given below.
Code
- package exceptionHandling;
- public class FinalizeExample {
- public void finalize() {
- System.out.println("finalize method called");
- }
- public static void main(String[] args) {
- FinalizeExample f = new FinalizeExample();
- f = null;
- System.gc();
- }
- }
Output
In the example, shown above, we can see that finalize() method calls at the runtime before an object is garbage collected.
Summary
Thus, we learnt Final is a keyword, Finally is a block, Finalize is a method and also learnt their differences in Java with the example.