Garbage Collection in Java — Java Technical Interview Questions & Answers
Garbage Collection in Java
Garbage Collection in Java
- Garbage collection frees heap objects that nothing points to anymore. You don’t call free() like C++. The JVM decides when to collect.
- System.gc() is only a hint, not a force. Memory leaks still happen if you keep unwanted references (static lists, caches).
- Don’t say “Java has no memory problems”. GC helps; leaks are still possible.
- Let's take this on the board with one tiny Main class — no extra files. Garbage Collection in Java — output: a is null; GC may collect the unused String. After a = null, no reference remains — GC can free it. Start from main, go line by line, and stop at each print. That output is the proof for Garbage Collection.
Technical Interview Tip: GC frees unreachable objects. You cannot force it. Leaks still possible if references remain.
Code Examples for Garbage Collection in Java
Example
// GC
public class Main {
public static void main(String[] args) {
String a = new String("temp");
a = null;
System.out.println("a is null; GC may collect the unused String");
System.gc();
}
}Garbage Collection in Java — output: a is null; GC may collect the unused String. After a = null, no reference remains — GC can free it.
How to Explain Garbage Collection in Java to an Interviewer
What does GC free?
Unreachable heap objects
Does System.gc() force GC?
No Only a hint