When a garbage collector determines that no more references are made to a particular object, then the finalize() method is called by the garbage collector on that object. The finalize() method requires no parameters and does not return a value.
A program that demonstrates the finalize() method in Java is given as follows:
import java.util.*; public class Demo extends GregorianCalendar { public static void main(String[] args) { try { Demo obj = new Demo(); System.out.println("The current time is: " + obj.getTime()); obj.finalize(); System.out.println("The finalize() method is called"); } catch (Throwable e) { e.printStackTrace(); } } }
The current time is: Tue Jan 15 13:21:55 UTC 2019 The finalize() method is called
Now let us understand the above program.
In the main() method in class Demo, an object obj of Demo is created. Then the current time is printed using the getTime() method. The finalize() method is called. A code snippet which demonstrates this is as follows:
try { Demo obj = new Demo(); System.out.println("The current time is: " + obj.getTime()); obj.finalize(); System.out.println("The finalize() method is called"); } catch (Throwable e) { e.printStackTrace(); }