MODULE 1 · TOPIC 11 · VISUAL PROGRAMMING LAB

Java Memory Management

Explore stack frames, object references, heap reachability and garbage collection.

Browser-based simulations: change the inputs, trace the Java statements and inspect results. No arbitrary Java execution, real database, threads or file changes occur here.

1. Stack frames and local variables

Trace a method call, return value and frame removal.

Java example
Program / simulation outputConsole
Stack frame inspectorCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

Each invocation has a frame with locals and operand stack in the JVM model. Frames disappear when methods return. Actual JVM optimizations may differ.

Try and observe

Change x and inspect which variables disappear.

2. Heap, references and aliasing

Watch two references point to the same or distinct objects.

Java example
Program / simulation outputConsole
Live state / data blocksCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

Assignment copies references, not objects. Two aliases observe changes to the same object. Java passes reference values by value.

Try and observe

Set alias then separate; compare a.value.

3. Garbage collection — reachability

Remove references and inspect eligible objects.

Java example
Program / simulation outputConsole
Live state / data blocksCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

GC reclaims unreachable objects when the JVM chooses. A null assignment alone does not guarantee collection; another reference may keep the object reachable.

Try and observe

Choose no and compare reachability, not collection timing.

4. Hands-on practice and assessment

Programming challenge

Create two references to an object, set one to null, and explain why the object remains reachable. Draw the heap and stack at each stage.

Edit the scratchpad below. Copy your code into an actual Java project or IDE to compile and test it.

Quick assessment

Key points and real Java notes

Heap stores objects in the conceptual JVM model; class metadata and native memory are separate. Java GC does not close file handles reliably; use resource management. Memory leaks can still occur via retained references.