Java Interview Question

What is garbage collection in Java?

Updated 2026-08-16 · Beginner friendly
Quick answer

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.

Key takeaways
  • 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

In the interview

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.

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