Skip to content
C

Garbage Collection

Garbage Collection is the automatic process by which Java identifies and removes objects from the Heap that are no longer being used by the program, freeing up memory without the programmer needing to manually delete them.


1. What is Garbage Collection?

Garbage Collection is the automatic process by which Java identifies and removes objects from the Heap that are no longer being used by the program, freeing up memory without the programmer needing to manually delete them.

2. Why is it used?

In many other languages, developers must manually free memory, which can lead to mistakes like memory leaks or accessing memory that's already been freed. Java's automatic Garbage Collection removes this burden and reduces such memory-related bugs.

3. Real-Life Example

Think of a cleaning service that automatically removes unused, discarded items from a room, without you needing to manually take out the trash yourself every time something is no longer needed.

4. Syntax

java
// Not directly called by the programmer in normal use System.gc(); // requests garbage collection, though the JVM decides when it actually runs

5. Example Program

java
public class GarbageCollectionDemo { public static void main(String[] args) { String data = new String("Temporary data"); data = null; // object now has no references, eligible for garbage collection System.gc(); // requests JVM to run garbage collection System.out.println("Garbage collection requested."); } }

Output:

Garbage collection requested.

(Note: `System.gc()` is only a request — the JVM decides whether and when to actually run it.)

6. Key Points to Remember

  • An object becomes eligible for garbage collection once no part of the program holds a reference to it anymore.
  • System.gc() only suggests garbage collection to the JVM; it doesn't force it to happen immediately.
  • Garbage Collection removes the need for manual memory deallocation, unlike languages such as C/C++.