GCGrowCarrer

Stack, Heap and Garbage Collection

Locked

Lesson 24 of 60 · Memory · Challenging

Finish these first:Classes and Objects →Or pass the tests below to unlock it now.

1

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.
Key words (tap to learn):
2

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.

3

Quick check

Before writing code: What should `Solution.sameObject("a","a")` return when your implementation of Stack, Heap and Garbage Collection is working?

4

Your challenge

2 sample tests, 1 hidden

Write static boolean sameObject(Object a, Object b) using reference equality.

Stuck? Get a hint (free)
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.

Mastery0%

Learn this first

Opens up next

This is the last lesson in this branch.