- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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(); }
- Related Articles
- Garbage collection in Java
- Java Garbage collection
- How many times finalize method will be invoked? who invokes finalize() method in Java?
- Garbage Collection in Python
- What is the purpose of overriding a finalize() method in Java?
- Garbage collection(GC) in JavaScript?
- How can we call garbage collection (GC) explicitly in Java?
- How to make an object eligible for garbage collection in Java?
- What is garbage collection in C#?
- Destroying Objects (Garbage Collection) in Python
- Destructors and Garbage Collection in Perl
- What is JavaScript garbage collection?
- How to prevent object of a class from garbage collection in Java?
- How does garbage collection work in Python?
- How to force garbage collection in C#?

Advertisements