← Chapter 5 — Arrays, Memory & Methods

20. Stack & Heap Memory

mixed

Description

Java manages memory automatically, but a simple mental model helps you understand variables. Local variables and method calls are associated with the stack, while objects and arrays live on the heap.

A reference variable holds a way to reach an object, not a full copy of that object. Multiple references can point to the same object.

A simplified view of local references and heap objects.
A simplified view of local references and heap objects.

Subtopics

Stack frames

Description

Each method call has local working space.

Explanation

When the method returns, its local frame is removed.

Example

int score = 90;

Heap objects

Description

Objects are created with new.

Explanation

Garbage collection may reclaim unreachable objects.

Example

int[] scores = new int[3];

Explanation

Do not try to manually free Java objects. Instead, avoid retaining references you no longer need and use try-with-resources for files, sockets, and similar resources.

Example

public class MemoryDemo {
    public static void main(String[] args) {
        int[] scores = {70, 80, 90};
        int[] sameScores = scores;
        sameScores[0] = 75;
        System.out.println(scores[0]);
    }
}

Key points

  • Local method work uses stack frames.
  • Objects and arrays are heap allocated.
  • References can share one object.

Open reference