Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality. The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Along with this, there are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:
Sr. no. | Key | final | finally | finalize |
---|---|---|---|---|
1. | Definition | final is the keyword and access modifier which is used to apply restrictions on a class, method or variable. | finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. | finalize is the method in Java which is used to perform clean up processing just before object is garbage collected. |
2. | Applicable to | Final keyword is used with the classes, methods and variables. | Finally block is always related to the try and catch block in exception handling. | finalize() method is used with the objects. |
3. | Functionality | (1) Once declared, final variable becomes constant and cannot be modified. (2) final method cannot be overridden by sub class. (3) final class cannot be inherited. | (1) finally block runs the important code even if exception occurs or not. (2) finally block cleans up all the resources used in try block | finalize method performs the cleaning activities with respect to the object before its destruction. |
4. | Execution | Final method is executed only when we call it. | Finally block is executed as soon as the try-catch block is executed. It’s execution is not dependant on the exception. | finalize method is executed just before the object is destroyed. |
Java final Example
Let’s consider the following example where we declare final variable age. Once declared it cannot be modified.
FinalExampleTest.java
Output:
In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final using the final keyword.
Java finally Example
Let’s see the below example where the Java code throws an exception and the catch block handles that exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.
FinallyExample.java
Output:
Java finalize Example
FinalizeExample.java
Output: