All the three keywords final, finally and finalize() plays a very important role in JAVA. Final is a keyword used for declaration of variable which cannot be edited, finally is a segment of code used for code cleanup in case of an exception whereas finalize is a method used for object cleanup before garbage collection.
Use of final, finally and finalize
Final:- It is used in the following three cases:
If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
If a method is marked as final then the method cannot be overridden by any other method.
If a class is marked as final then this class cannot be inherited by any other class.
Finally:- If an exception is thrown in try block then the control directly passes to the catch block without executing the lines of code written in the remainder section of the try block. In case of an exception we may need to clean up some objects that we created. If we do the clean-up in try block, they may not be executed in case of an exception. Thus finally block is used which contains the code for clean-up and is always executed after the try …catch block.
Finalize:- It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. Finalize() method is used for performing code clean-up before the object is reclaimed by the garbage collector.
Latest posts by Shankar Morwal (see all)
- Upgrade node.js version in ubuntu 14 or ubuntu 16 - May 8, 2017
- Angular 4 will be out soon, Everything you need to know - February 20, 2017
- Installing teamcity 10.0.4 on ubuntu server - January 17, 2017