What is the purpose of finalization

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

In Java, finalization refers to the process of cleaning up resources or performing some specific actions before an object is garbage-collected. The finalize() method is a method of the Object class, and it gets called by the garbage collector before reclaiming the memory occupied by the object.

The purpose of finalization in Java is to provide a mechanism for performing cleanup operations, such as releasing system resources (closing files, network connections, etc.) or releasing resources acquired during the object’s lifetime. It allows the developer to define custom cleanup logic that will be executed before the object is garbage-collected.

However, it’s important to note that relying on finalize() for resource cleanup is not considered a good practice in modern Java programming. This is because the garbage collector may not run at predictable times, and there’s no guarantee that finalize() will be called promptly. Instead, the try-with-resources statement and the AutoCloseable interface are recommended for resource management in Java, as they provide a more deterministic way to handle resource cleanup.