Introduction
The keywords final, finally, and finalize are used in exception handling in Java. Each of these terms serves a distinct purpose. The primary distinction between final, finally, and finalize is that final is an access modifier, finally is an exception handling block, and finalize is an object class function.
Furthermore, there are numerous distinctions between final, finally, and finalize. The following are the distinctions between final, finally, and finalize:
Key | final | finally | finalize |
Definition | final is a keyword and access modifier that is used to restrict access to a class, method, or variable. | Finally, the block in Java Exception Handling executes the critical function whether or not the exception occurs | In Java, the finalize method is used to do cleanup procedures immediately before an object is garbage collected. |
Applicable to | With classes, methods, and variables, the final keyword is utilized. | In exception handling, the finally block is usually associated with the try and catch block. | The finalize() method is applied to objects. |
Functionality |
(1) Once declared, the final variable is fixed and cannot be changed. (2) A subclass cannot override the final method. (3) The final class is not inheritable. |
(1) The finally block executes the critical code whether or not an exception occurs. (2) The finally block cleans up all of the resources that were used in the try block. |
Before an item is destroyed, cleaning tasks are carried out using the finalize method. |
Execution | Only when we call the final method is it actually used. |
After the try-catch block, the finally block is carried out. The exception has no bearing on how it is carried out. |
Just before the object is destroyed, the finalize method is called. |
Must Read Static Blocks In Java and Fibonacci Series in Java.
Example of Final Keyword
Let's have a look at the example below where the final variable "name" is declared. It cannot be changed once it is stated.
Example.java
class Example{
// declaring a final variable
final String name = "Soham";
void disp(){
// reassigining the name variable
// that throws compile time error
name = "Ganesh";
}
public static void main(String[] args) {
Example obj = new Example();
// executing disp method;
obj.disp();
}
}
Output
Example.java:8: error: cannot assign a value to final variable name
name = "Ganesh";
^
1 error
Try it on online java compiler.
A variable has been designated final in the example above. The final keyword can also be used to designate methods and classes final.
Also see, Swap Function in Java