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.
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.
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