Java / Java 17 Garbage Collection Interview Questions
What is the purpose of a garbage collector in the JVM?
The garbage collector exists to guarantee memory safety without requiring the developer to manually track object lifetimes.
Specifically, it eliminates dangling-pointer and use-after-free bugs by only reclaiming objects once nothing can reach them, it prevents unbounded memory growth (and eventual OutOfMemoryError) by continuously recycling dead objects, and in most collectors it also compacts the heap - sliding live objects together - so free space doesn't fragment into unusable slivers.
By taking on this bookkeeping, the JVM lets application code focus on logic rather than memory ownership rules, which is one of the core productivity and safety trade-offs of managed runtimes versus languages like C or C++.
More Related questions...