Using the finalize() method in Java Garbage Collection

Java 8Object Oriented ProgrammingProgramming

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:

Example

 Live Demo

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();
      }
   }
}

Output

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();
}
raja
Published on 19-Feb-2019 05:43:01
Advertisements