📘 Lesson · Lesson 45
Garbage Collection
Garbage Collection
What is Garbage Collection?
Garbage Collection (GC) automatically frees memory by removing objects that are no longer used — so you do not manually free memory like in C/C++.
How it Works
- Objects with no references left become "garbage".
- The JVM's garbage collector finds and removes them automatically.
- You can suggest it with
System.gc(), but the JVM decides when.
Making an Object Eligible
String s = new String("hello");
s = null; // old object now has no reference -> eligible for GC
Summary
- GC automatically removes unreferenced objects to free memory.
- No manual free() needed; setting a reference to null helps.
Garbage Collection क्या है?
Garbage Collection (GC) उन objects को हटाकर memory अपने आप free करता है जो अब use नहीं होते — तो C/C++ की तरह manually memory free नहीं करनी पड़ती।
यह कैसे काम करता है
- जिन objects का कोई reference नहीं बचता वे "garbage" बन जाते हैं।
- JVM का garbage collector उन्हें ढूंढकर अपने आप हटाता है।
- आप
System.gc()से सुझाव दे सकते हैं, पर JVM तय करता है कब।
Object को Eligible बनाना
String s = new String("hello");
s = null; // पुराने object का अब कोई reference नहीं -> GC के लिए eligible
सारांश
- GC unreferenced objects को अपने आप हटाकर memory free करता है।
- Manual free() नहीं चाहिए; reference null करना मदद करता है।