Memory Management & Garbage Collection
Prerequisites: Reflection & annotations
Java manages memory automatically — objects live on the heap,
and the garbage collector (GC) periodically reclaims any object
no longer reachable from a running thread, so there's no manual
free() or delete as in C or C++.
void createObjects() {
for (int i = 0; i < 1000; i++) {
String temp = "item " + i; // eligible for GC once the loop moves on
}
}
A StackOverflowError happens when the call stack (holding local
variables and return addresses for each active method call) grows
too deep, usually from unbounded recursion; an OutOfMemoryError
happens when the heap genuinely runs out of room even after
garbage collection.
Common mistakes
- Holding a reference to an object longer than needed (e.g. in a static collection that keeps growing) — this prevents the GC from ever reclaiming it, a pattern known as a memory leak even in a garbage-collected language.