In Java, there is no traditional destructor function. Instead, Java uses garbage collection to manage memory, eliminating the need to explicitly define destructors as in C++ for releasing resources.
However, Java provides a method called finalize(), which serves as a counterpart to the destructor function. The finalize() method is invoked before the garbage collector reclaims an object's memory, for performing cleanup tasks such as closing file streams or network connections.
javaprotected void finalize() throws Throwable { try { // Cleanup code, e.g., closing files } finally { super.finalize(); } }
Relying on finalize() for resource cleanup is not recommended due to its unpredictable execution timing. The preferred approach is to use the try-with-resources statement or explicitly call cleanup methods, such as invoking close().