What are the young and old generations in the Java heap?
New objects start in the young generation, which is collected often and cheaply because most objects die quickly. Objects that survive several collections are promoted to the old generation, which is collected less often.
Explain it simply
Think of a tiffin box lunch: most of what you buy at the canteen is eaten and the wrapper thrown away within minutes. Only a few things, like a water bottle, are kept for months. The JVM separates "short-lived stuff" from "long-lived stuff" so it can clean the first group often without disturbing the second.
Example
// Conceptual layout
// Heap
// |-- Young generation: Eden + Survivor 0 + Survivor 1
// |-- Old generation (Tenured)
for (int i = 0; i < 1_000_000; i++) {
String temp = "order-" + i; // dies young: cleaned in a minor GC
}
static final java.util.Map<Integer, String> CACHE = new java.util.HashMap<>(); // lives long: ends in old genWhat to say in the interview
"The weak generational hypothesis says most objects die young. New objects are allocated in Eden. A minor GC copies the survivors into a survivor space and increments their age. After enough survivals, an object is promoted to the old generation. Minor collections are quick; a collection of the old generation takes longer. Modern collectors like G1 split the heap into regions but keep the same idea. A full GC that scans everything is the most expensive."
Common mistakes
- Thinking the generations are separate programs. They are areas of one heap.
- Allocating huge long-lived objects and expecting minor GC to clean them.