4. How Java Works
Programming Project 2022/23

4.4. Java Memory Model

JVM's Memory Area

jvm architecture

Image source

The stack

Each thread running in the Java virtual machine has its own thread stack, which contains information about which methods the thread has called (the call stack).

It also contains all the local variables and parameters.

Primitive local variables are stored on the thread stack.

Reference local variables point to objects in the heap.

The heap

The heap contains all objects created in your Java application, regardless of which thread created the object.

It does not matter if an object was created and assigned to a local variable, or created as a member variable of another object, it will be stored on the heap.

If an object is not referenced by any reference variable, it becomes garbage!

From time to time, the JVM will trigger the garbage collector to remove these unused objects from memory.

Demo

Here is a step-by-step demo video of how the stack and the heap are used when executing a Java program.