What is the difference between final, finally and finalize() in Java?1. final – a key word / access modifier to define constants.
2. finally – The finally block always used in conjunction with try and catch blocks, except that, if try block uses System.exit(0) call. It is ensured that in event of an unexpected error / exception, the finally block performs the execution. Not only for exception handling, finally also even utilized for cleaning up the code, such as returning values, continue or break statement usage, closing streams etc. It is a good programming practice to use cleaning up the code in finally block, even though exceptions are not anticipated.
3. finalize() – This method is associated with garbage collection. Just before collecting the garbage by the system (discarding an object from its scope), this method is invoked automatically.
What is the difference between final, finally and finalize() in Java?Final:
- A final class variable is one whose value cannot be changed.
- A final method is one that cannot be overriden (define with new behaviour in subclasses).
- A final class cannot be inherited.
It is a block of statements that definitely executes after the try catch block.
This method will be executed when the object is garbage-collected.