Sobes.tech
Middle

How is memory organized in Java?

sobes.tech AI

Answer from AI

In Java, memory is managed automatically by the garbage collector and is divided into several regions:

  1. Heap:

    • Stores class objects and arrays.
    • Shared among all application threads.
    • Garbage Collector works with this region.
    • Divided into generations (Young, Old, Permanent).
  2. Stack:

    • Each thread has its own stack.
    • Stores local variables and references to heap objects.
    • Data is added and removed in LIFO order.
    • Automatically freed when the method finishes.
  3. Method Area / PermGen / Metaspace:

    • Stores information about loaded classes:
      • Class metadata.
      • Bytecode of methods.
      • Static variables.
      • Constant pool.
    • PermGen size was fixed; Metaspace uses native memory and can grow dynamically.
  4. Native Method Stacks:

    • Used for native method calls (e.g., C/C++).
    • Freed when native method finishes.
// Example of memory usage
public class MemoryExample {

    private String instanceVariable; // stored in Heap

    public void myMethod(int parameter) { // parameter stored in Stack

        int localVar = 10; // localVar stored in Stack

        String localString = "hello"; // "hello" in String Pool (part of Heap/Method Area), localString reference in Stack

        Object obj = new Object(); // Object in Heap, obj reference in Stack

        Integer wrapper = new Integer(5); // Integer in Heap, wrapper reference in Stack
    }

    public static void main(String[] args) {
        MemoryExample example = new MemoryExample();
        example.myMethod(20);
    }
}

Memory regions and their contents:

Region Location Contents Management
Heap Shared across JVM Objects, arrays Garbage Collector
Stack Per thread Local primitives, object references Automatic (on method finish)
Method Area / PermGen / Metaspace Shared across JVM Class metadata, static variables, bytecode, constants Garbage Collector (for classes and static data)
Native Stacks Per thread (during call) Native method variables and data Automatic (on native method finish)
How is memory organized in Java? — Android - sobes.tech