The heap is typically split into young/old generations: most objects die young, so collecting the young gen is cheap and frequent (minor GC). Surviving objects are promoted; old gen collections are rarer and usually more expensive.
Advanced answer
Deep dive
At a high level, GC:
Finds reachable objects (mark).
Reclaims memory of unreachable objects (sweep) and may compact to reduce fragmentation.
Generational GC is based on the “generational hypothesis”: most objects die young. So the heap is split:
Young gen (Eden + survivor spaces): collected often (minor GC) and usually fast.
Old gen: collected less often (major/mixed collections) and typically more expensive.
Practical view
Allocation is cheap; GC cost appears as pauses and CPU overhead.
Modern collectors (G1, ZGC, Shenandoah) trade throughput vs pause-time differently.
Common pitfalls
Thinking GC frees objects “when they go out of scope” (it’s reachability-based).
Creating lots of short-lived garbage in hot paths.