Table of Contents
Program on constructor and destructor in Java
Constructor In Java
Constructor is use to initialize objects. We can accept the values for variables during object creation.
- Constructor method name is exact same as the class name.
- There is no need of return type for constructor.
- Constructor gets call when object is instantiated.
Click here for more information.
Destructor In Java
In java there is not such method as destructor, which we can call. Java provides its alternative named “finalize()“.
Java uses Garbage Collector instead of Destructor. Garbage Collector deletes the unused objects from memory to make some space in memory. The garbage collector runs on the JVM itself. Garbage Collector runs finalize method hence we write our code in finalize method.
Suppose we have created reference variable for database, sockets, etc. and we want to destroy these reference variable once we close the program. We can write closing code in finalize method which will get executed by Garbage Collector.
Java Constructor and Destructor program
While loop go on and on and it will start instantiating object. Object will get saved in Heap memory once JVM will run Garbage Collector to free some memory. Hence if you run following program you have to wait till Garbage Collector runs.
Garbage Collector will execute finalize method hence we can see finalize method running in between without even calling.
Call Garbage Collector
We can call Garbage Collector explicitly using “System.gc()”.
Connect with us on following platforms
PRACTICALS/PRACTICE PROGRAM IN Java