Sobes.tech
Senior

How is memory organized in Java (JVM)? What are the areas: stack, heap?

sobes.tech AI

Answer from AI

Memory in JVM is divided into several key areas:

  • Heap — an area for storing objects and arrays. All objects created via new are placed in the heap. The heap is managed by the garbage collector, which frees memory from unused objects.

  • Stack — an area of memory for storing method call frames. Each method call creates a frame that contains local variables, method parameters, and return address. The stack operates on a LIFO principle and is managed automatically by the JVM.

  • Metaspace — an area for storing class metadata loaded by the JVM, including information about methods, fields, etc. In older JVM versions, this was called PermGen.

  • Registers and other internal areas — used for JVM operation but less noticeable to developers.

Example:

public void example() {
    int a = 10; // stored in the stack
    Object obj = new Object(); // object in the heap, reference in the stack
}

Thus, the stack manages calls and local variables, while the heap stores objects with dynamic lifetimes.