What is garbage collection in Java?
Garbage collection is the process where the JVM automatically finds objects that are no longer used and frees their memory. An object becomes eligible when nothing references it any more. This frees developers from manually releasing memory, which prevents many memory leaks and crashes common in languages without it.
- Garbage collection automatically frees heap memory that objects no longer reference.
- It removes the need for manual memory freeing and prevents most memory leaks.
- You cannot force it, but System.gc() can suggest it run.
Why it exists
In some languages you must free memory by hand, which is error prone. Java runs a garbage collector in the background that reclaims heap memory for objects you can no longer reach, so you can focus on logic instead of memory bookkeeping.
String s = new String("data");
s = null; // the object is now unreachable and eligible for GC
Key points
- An object is collected when it is unreachable, not the instant you finish with it.
- You cannot force collection, but System.gc() is a hint the JVM may ignore.
- Modern collectors work in generations, since most objects die young.
A common trap is claiming you can force garbage collection. Be precise: you can suggest it with System.gc(), but the JVM decides when it runs. That accuracy sets you apart from candidates who overstate control.
Frequently asked questions
How does the garbage collector know an object is unused?
It considers an object eligible for collection when nothing reachable from active code references it anymore, so it can never be used again.
Can Java still have memory leaks?
Yes. If you keep unwanted references, for example in a static collection that grows forever, the objects stay reachable and are never collected.
Common follow up questions
Related interview questions
Want the full Java guide?
Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Java guide All Java questions