What is garbage collection in Java?

Why do we need to deallocate memory?

In C and C++, a programmer must manually invoke free() and delete() respectively to destroy or free up dynamically allocated memory for more objects. We don’t need to do this in Java, as it is done automatically using garbage collection.

Garbage collection in Java

The Java Runtime Environment (JRE) performs this task itself, which is known as garbage collection. Although we can manually include the method gc() to observe how garbage collection works in Java, this is optional.

Types of garbage in a program

Usually, programmers come up with two types of garbage in a code.

1. Syntactic garbage

A good tester or developer knows how to review the code manually. While reviewing, a programmer can tell that this specific code will lead to garbage at some point and occupy unnecessary memory. We can then sort it out at that exact moment.

2. Semantic garbage

Sometimes the programmer is unable to determine whether or a particular line of code will lead to garbage. We observe such code at runtime execution.

Advantages of garbage collection

Garbage collection is beneficial because it reduces a programmer’s workload and increases the efficiency of the project.

Some more advantages of garbage collection include:

  1. Automatically handles deallocation of unused objects.
  2. Frees up memory for new objects.
  3. Reduces application program bugs.

The gc() method

We can invoke a garbage collector in our program using the built-in method gc().

The gc() method performs cleanup of code and releases unnecessary occupied memory.

Places where garbage collection works

Although garbage collection in Java works automatically, there are still places where we must indicate the compiler to activate the garbage collector.

In other words, we must make the code eligible to perform garbage collection.

An object in Java only becomes eligible if it is unreachable (i.e., an object loses its value and points towards a null location).

Code

Like before, we can manually use the garbage collector to learn how it works and acts in different conditions.

Let’s observe the below implementation of the garbage collector in Java.

class GarbageCollector {
public static void main( String args[] ) {
GarbageCollector gc1 = new GarbageCollector();
// requesting Java garabage collector
System.gc();
}
}

Explanation

The above piece of code implements a simple class, GarbageCollector, that includes a dynamically allocated object named gc1 of the same class.

We invoked the System.gc() method to run the garbage collector. The program returns no output, but shows that the execution is successful.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved