
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using the finalize Method in Java Garbage Collection
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
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(); }
Advertisements