Stack, Heap and Garbage Collection
LockedLesson 24 of 60 · Memory · Challenging
Finish these first:Classes and Objects →Or pass the tests below to unlock it now.
The big idea
Locals and call frames live on the stack; objects live on the heap. The garbage collector frees objects that are unreachable.
Think of it like this: Think of stack frames as sticky notes on your desk for the current function call, and the heap as a shared warehouse where variables hold reference tickets (#ref1) to containers.
Read the lesson
Locals and call frames live on the stack; objects live on the heap. The garbage collector frees objects that are unreachable. Memory leaks happen when you keep references (static collections, listeners).
String a = new String("x");
String b = a; // same object, two references
a = null; // object still reachable via b
Use WeakReference and bounded caches to avoid leaks.
Quick check
Before writing code: What should `Solution.sameObject("a","a")` return when your implementation of Stack, Heap and Garbage Collection is working?
Your challenge
Write static boolean sameObject(Object a, Object b) using reference equality.
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
See how Java compares side-by-side with Python.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Stack, Heap and Garbage Collection.
Learn this first
- Classes and ObjectsNot yet
Opens up next
This is the last lesson in this branch.