e Learning

What is Garbage Collection in Java

In simple, Garbage Collection in Java is objects that are not in use or the objects that has no reference variable. In Java when a new Object Creates it’s created in Java heap memory and it will be kept in heap memory as long as the object has a reference variable in the stack memory. But once no variables are referring to the object that object is  eligible to the Java garbage collection. Then the programme called Garbage collector runs and destroy the objects that are in the garbage collection.

What is Garbage Collection in Java

How the garbage collector works in Java

The Garbage collector is a program runs inside The Java Virtual Machine(JVM) that find and destroys useless objects and reclaims the memory space.In Java programming language programmer cannot destroy a useless object, it is handle by the garbage collector. But still the programmer can make an object eligible for garbage collection by setting it’s reference variable to null, which is called as Nullifying Reference to the Variable.

For Example we have a class called Student and lets think We create a new object from the Student class with it’s reference variable as student1.

Students student1 = new Students();

Now if we want to the make Student object we created to be eligible to garbage collection , we can set value of the reference variable student1 to be null.

student1 = null;

Now the garbage collector can destroy and free the memory space acquired by Student Object.