Java Learner logo

Module 2: Variables, Data Types, and Operators

Lesson focus

Memory Allocation: Stack vs. Heap

A simplified explanation of how Java manages memory, focusing on the difference between the Stack (for primitive types and method calls) and the Heap (for objects).

Two Key Memory Areas: When your Java program runs, the JVM allocates memory from two main areas: the Stack and the Heap.

The Stack:

  • What it is: A highly organized and fast memory area that works on a Last-In, First-Out (LIFO) principle.
  • What it stores: When a method is called, a new block (called a "stack frame") is pushed onto the stack. This frame holds all the local variables (variables declared inside the method) and primitive type variables. It also stores a reference to the object on the heap.
  • Lifecycle: When the method finishes executing, its stack frame is popped off the stack, and all the variables in it are destroyed. This memory management is automatic and very fast.

The Heap:

  • What it is: A large, less organized pool of memory.
  • What it stores: This is where all objects are created. When you use the new keyword (e.g., new String("Hello")), the object is allocated on the Heap.
  • Lifecycle: Objects on the Heap are not tied to any particular method. They exist as long as they are being referenced by something (e.g., a variable on the stack). The Garbage Collector (GC) is a background process that automatically finds and deletes objects on the Heap that are no longer referenced, freeing up memory.

Analogy: Imagine the Stack is a series of desks in an office. When an employee (method) starts work, they get a desk and put their tools (local variables) on it. When they finish, they clear the desk and leave. The Heap is a large shared supply closet. When an employee needs a complex piece of equipment (an object), they request it from the closet. They keep a note on their desk (a reference) pointing to that equipment. When no one has a note pointing to that equipment anymore, the cleaning crew (Garbage Collector) removes it from the closet.

Diagram Description: A diagram showing the Stack on one side and the Heap on the other. The Stack has frames for main() and doWork(). The main frame has a primitive int x = 10. The doWork frame has a reference variable myString with an arrow pointing to a String object in the Heap that contains the value "Hello".

public void myMethod() {
    int localValue = 20; // Stored on the Stack
    String message = new String("Hi!"); // `message` is a reference on the Stack, 
                                      // the String object itself is on the Heap.
} // When myMethod ends, `localValue` and `message` are gone. 
  // The "Hi!" object is now eligible for garbage collection.

Lesson quiz

When you declare `int x = 5;` inside a method, where is the value `5` stored?

Next lesson →