What is Garbage Collection in Java?

What is Garbage Collection in Java?

Garbage Collection in Java is a process by which the programs perform memory management automatically. The Garbage Collector(GC) finds the unused objects and deletes them to reclaim the memory. In Java, dynamic memory allocation of objects is achieved using the new operator that uses some memory and the memory remains allocated until there are references for the use of the object.

When there are no references to an object, it is assumed to be no longer needed, and the memory, occupied by the object can be reclaimed. There is no explicit need to destroy an object as Java handles the de-allocation automatically.

The technique that accomplishes this is known as Garbage Collection. Programs that do not de-allocate memory can eventually crash when there is no memory left in the system to allocate. These programs are said to have memory leaks.

Garbage collection in Java happens automatically during the lifetime of the program, eliminating the need to de-allocate memory and thereby avoiding memory leaks.

In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically using free() function. This is where Java memory management leads.

Note: All objects are created in Heap Section of memory. More on this in a later tutorial.

Example: To Learn Garbage Collector Mechanism in Java

Step 1) Copy the following code into an editor.

class Student{
int a;
int b;
  public void setData(int c,int d){
  public void showData(){
    System.out.println("Value of a = "+a);
    System.out.println("Value of b = "+b);
  public static void main(String args[]){
    Student s1 = new Student();
    Student s2 = new Student();
    //Student s3;

Step 2) Save, Compile and Run the code. As shown in the diagram, two objects and two reference variables are created.

 Garbage Collector Mechanism

Step 3) Uncomment line # 20,21,22. Save, compile & run the code.

Step 4) As shown in the diagram below, two reference variables are pointing to the same object.

Garbage Collector Mechanism

Step 5) Uncomment line # 23 & 24. Compile, Save & Run the code

Step 6) As show in diagram below, s2 becomes null, but s3 is still pointing to the object and is not eligible for java garbage collection.

 Garbage Collector Mechanism

Step 7) Uncomment line # 25 & 26. Save, Compile & Run the Code

Step 8) At this point there are no references pointing to the object and becomes eligible for garbage collection. It will be removed from memory, and there is no way of retrieving it back.

 Learn Garbage Collector

How to delete an object in Java?

1) If you want to make your object eligible for Garbage Collection, assign its reference variable to null.

2) Primitive types are not objects. They cannot be assigned null.

How to delete an object in Java