What are finally and finalize in Java?
920
24-Nov-2021
Updated on 16-Jun-2023
Aryan Kumar
16-Jun-2023Finally and finalize are two keywords in Java that are used for exception handling and garbage collection, respectively.
Finally is a block of code that is always executed, regardless of whether or not an exception is thrown. This can be used to ensure that important cleanup code is always executed, even if an exception is thrown and the rest of the code in the try block is not executed.
Finalize is a method that is called by the garbage collector when an object is about to be garbage collected. This method can be used to perform cleanup tasks on the object, such as closing files or releasing other resources.
Here is an example of how to use the finally keyword:
Code snippet
Here is an example of how to use the finalize method:
Code snippet
Mukul Goenka
24-Nov-2021Finally block is used with a try-catch block to put the code that you always want to get executed even the execution is thrown by the try-catch block. Finally is just used for releasing the resources which were created by the try block.
Finalize() is a special method in Object class that we can override in our classes. Finalize() is called by the Garbage collector to collect the garbage value when the object is getting it. This method is generally overridden to release the system resources when garbage value is collected from the object.