What is the difference between final, finally, and finalize?
Despite their similar sounding names, final, finally and finalize have very different purposes. To speak in very general terms, final is used to control whether a variable, method, or class is “changeable.” The finally keyword is used in a try/ catch block to ensure that a segment of code is always executed. The finalize() method is called by the garbage collector once it determines that no more references exist.
Further detail on these keywords and methods is provided below.
The final statement has a different meaning depending on its context.
1.When applied to variable(primitive): The value of the variable cannot change.
2. When applied to a variable(reference): The reference variable cannot point to any other object on the heap.
3. When applied to a method: The method cannot be overridden.
4. When applied to a class: The class cannot be subclassed.
There is an optional finally block after the try block or after the catch black. Statements in the finally block will always be executed (except if Java Virtual Machine exists from the try black). The finally black is used to write the clean-up code.
The finalize() method is called by the garbage collector when it determines that no more references exist. It is typically used to clean up resources, such as closing a file.