DEV Community

Cover image for HOW JAVA MEMORY WORKS
betpido
betpido

Posted on

HOW JAVA MEMORY WORKS

In Java, memory is divided into two parts: stack memory and heap memory.

Stack memory is used for static memory allocation and the execution of a thread.

It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.

Access to this memory is in Last-In-First-Out (LIFO) order. Whenever we call a new method, a new block is created on top of the stack which contains values specific to that method, like primitive variables and references to objects.

When the method finishes execution, its corresponding stack frame is flushed, the flow goes back to the calling method, and space becomes available for the next method.

Heap memory is used for the dynamic memory allocation of Java objects and JRE classes at runtime.

New objects are always created in heap space, and the references to these objects are stored in stack memory.

These objects have global access and we can access them from anywhere in the application.

Top comments (0)