Loading content...
Loading content...
Garbage Collection (GC) in Java is an automatic memory management process handled by the JVM.
It finds and removes unused objects from heap memory so developers don’t need to free memory manually.
Prevents memory leaks
Frees unused heap memory
Improves application performance
Avoids manual memory handling (unlike C/C++)
An object becomes garbage when:
No reference points to it
It’s no longer reachable from the program
plaintext
Student s = new Student();
s = null; // object becomes eligible for GCGC works in 3 main steps:
JVM identifies which objects are still in use
Unused objects are marked as garbage
JVM removes the marked (unused) objects
Memory is freed
Remaining objects are rearranged
Prevents memory fragmentation
JVM decides automatically
Runs when heap memory is low
Developer cannot force GC
plaintext
System.gc(); // Request only, not guaranteedplaintext
protected void finalize() {
// cleanup code
}⚠️ Deprecated (avoid using it)
Assign null
Reassign reference
Object inside method ends
Circular references without external reference
✔ Automatic memory management
✔ Prevents memory leaks
✔ Improves code reliability
✔ No manual free() required
Garbage Collection in Java is an automatic process by JVM to remove unused objects from heap memory to free space and improve performance.