Table of Contents
Program on constructor and destructor in Java
Write a Java program that demonstrates the use of constructor and destructor.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class DestructorDemo { public static void main(String[] args) { while(true) { new Itvoyagers(); } } } class Itvoyagers { public Itvoyagers() { System.out.println(" This is constructor for Itvoyagers class store at : "+this); } protected void finalize() { System.out.println(" This is finalize method for Itvoyagers class store at : "+this); } } |
Output
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()”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class DestructorDemo { public static void main(String[] args) { new Itvoyagers(); System.gc(); } } class Itvoyagers { public Itvoyagers() { System.out.println(" This is constructor for Itvoyagers class store at : "+this); } protected void finalize() { System.out.println(" This is finalize method for Itvoyagers class store at : "+this); } } |
Output

PRACTICALS/PRACTICE PROGRAM IN Java
CHECKOUT OTHER RELATED TOPICS
