Java Memory Structure

Author: Tatyana Milkina

Java Memory Structure

Memory structure in Java is quite complex, but at the initial stage of learning, we will study its two main areas: Stack and Heap.

1. Heap Memory

The Java Heap is used by the Java Runtime to allocate memory for objects and JRE classes. Every time a new object is created, it happens in the Heap. This is where the Garbage Collector works: it reclaims memory by deleting objects that no longer have any active references.

Any object created in the Heap has global access and can be referenced from any part of the application.

2. Stack Memory

What is the Stack? Stack memory in Java operates according to the LIFO (Last-In-First-Out) principle. Whenever a method is invoked, a new block (frame) is created in the stack memory to hold primitive values and references to other objects within that method. As soon as the method completes its execution, the block is discarded, making the space available for the next method.

The size of the Stack is much smaller than the volume of memory in the Heap.

Stack vs Heap: Key Differences

Whenever an object is created, it is always stored in the Heap, while the Stack memory contains a reference to it. Stack memory only holds local variables of primitive types and references to objects in the Heap.

The following logic illustrates the difference between creating primitive and reference variables. If a primitive local variable int a = 10 is created, its value is stored directly in the Stack. When a reference variable Test a = new Test() is created, the object itself is created in the Heap, while the variable Test a (the reference) resides in the Stack. The value of the variable Test a is the memory address of the object in the Heap.

Структура памяти в Java фото

Constructor code should only deal with object initialization. You should avoid calling other methods from a constructor, except for those marked as final. A method might be overridden in a subclass and distort the object initialization process.

Read also:
Comments