Skip to main content

Command Palette

Search for a command to run...

Memory in Programming — Stack vs Heap

Your Desk vs Your Storage Room

Updated
•7 min read•View as Markdown
Memory in Programming — Stack vs Heap
S
Senior Software Engineer with 7+ years in Java, Spring Boot, and scalable backend systems. I help engineers crack backend/full-stack interviews, improve system design, and transition into cloud and AI with practical, real-world guidance.

Story Time

Imagine you’re working in an office and as you all would know, you have two places to keep things, your desk or storage room. Your desk is normally small, neatly organized (who wants to work in a clutter right!!), everything is within arm’s reach for easy access and the things on there will be things you use it for quick tasks.

On the other hand, storage room is much bigger, less organized (I dump stuff there.. just don't wanna think about it), store large or complex items and takes a bit more effort to access

Now think about your work you keep current documents and notes on your desk and big files, archives, and bulky items in the storage room. This is exactly how memory works in a program.

In programming the desk translates to Stack and storage room translates to Heap.

What is “Memory” in a Program?

When a program runs, it needs space to store variables, keep track of function calls and hold objects and data. This space is called memory (RAM). Think of it as the working space your program uses while it is running. This is similar to saying you need space to keep your files, notes, etc. when you work.

Every time you write something like

int a = 10;

The program needs to store that value (10) somewhere or when you call a function

sum(5, 3);

The program needs to remember inputs (5, 3) and track where to return after execution and that's where Memory(Stack and Heap) come in.

What is the Stack?

Now let's go back to the office analogy, back to the desk. It has limited space, is highly organized and works in a strict order (you might have attached sticky notes to mark and sort the files based on some form of priority)

The Stack works the same way. The key idea behind Stack is that it stores temporary, short-lived data in a structured way. The stack follows LIFO - Last In, First Out. For simplicity you can think of it like stacking plates, you place a plate and when you place a second one, it goes on top. Similarly when you remove a plate the one you want to remove comes from top.

Now the next obvious question is what goes on the stack? As we mentioned in the desk analogy its things that you need immediately to finish the work you are doing. In case of programs that translates to function calls, local variables and method parameters.

void greet() {
    int x = 10;
}

When greet() runs a new stack frame is created and x is stored in that frame. And when the function ends the frame is removed and memory is freed instantly.

This is why an error message in Java is called a stack trace, as it traces the stack from the outermost method to all the inner methods.

What is the Heap?

Time to go back to the office analogy again one more time, this time to the storage room. The storage room obviously has more space than a desk, less organized as its more like a place to dump things that we need but immediately and stores large or complex items.

The Heap memory works the same way. The key idea behind Heap is that it stores data that lives longer or is more complex.

Now following the thought process that we applied for Stack, the next obvious question is what goes in the Heap? As discussed above Heap stores things that are more or less passively needed for our work and too large and complex things that can't be stored/kept on the desk (Stack). These include objects, arrays and large data structures.

Person p = new Person();

In the example above, the reference p goes on stack and the actual object new Person() goes in heap.

Stack provides more structure and Heap gives flexibility, but with less structure. Another way to view this is Stack is optimized for speed Heap is optimized for flexibility.

One other key difference between Stack and Heap memory is that Stack is small in size, short lived and is garbage collected frequently while Heap has a larger size, longer memory retention and managed and garbage collected less frequently.

Step-by-Step: Function Call Example

public class Main {
    public static void main(String[] args) {
        int result = add(2, 3);
    }

    static int add(int a, int b) {
        int sum = a + b;
        return sum;
    }
}

Let’s walk through a simple program. Here is what happens in the memory

  • Step 1: First the main() method starts and a stack frame created for main. The variable result is declared and left empty for now.

  • Step 2: The method add(2, 3) is called and along with it a new stack frame created. The method parameters a = 2, b = 3 stored in stack

  • Step 3: Inside add() method the value sum = 5 stored in stack

  • Step 4: The add() stack frame is removed and 5 is returned to main

  • Step 5: Back in main() the variable result is set to 5

The key ting to note here is that everything here stayed in the stack because it was simple data.

When Does Heap Come Into Play?

class Person {
    String name;
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.name = "Sreeram";
    }
}

Let’s take another example. In the above program

  • Step 1: First the main() method starts and a stack frame created for main.

  • Step 2: The reference p is stored in stack and the object new Person() is created in heap

  • Step 3: The value "Sreeram" stored in heap (string pool area conceptually.. Ill explain this later on under a separate blog)

The key thing to note here is Stack holds the reference, Heap holds the actual data

Relationship Between Stack and Heap

This is where what we have learned so far comes together. For simplicity let us think like this, Stack is what you’re working with right now and Heap is where the actual data lives

When data is simple the value is directly stored in Stack

int x = 10;
Stack:                          Stack:
  x   ───────────────►  10

When data is complex the stack doesn’t store the full object, it stores a reference (pointer) to the heap.

Person p = new Person();
Stack:                                 Heap:
  p   ───────────────► { name: "Sreeram" }

This is the key connection: The stack uses references to access data stored in the heap.

Important Note (Reality Check)

Different languages handle memory differently. For example languages like Java and Python manages memory automatically, whereas in C/C++ memory control needs to be managed manually. But the concept of Stack vs Heap still applies everywhere

Why Stack Overflow Happens

As we have discussed above, Stack has limited space. When the space in Stack is full and we try to keep adding new stack frames we get StackOverflowError. A simple analogy would be if your desk keeps getting new files but you never remove anything, eventually desk collapses due to the weight of the files placed on it.

One of the most common cause for stack overflow is recursive calls without any means to exit the recursion.

void infinite() {
    infinite();
}

In the above example each call creates a new stack frame and we can see that the stack keeps growing and growing. Eventually you reach a situation where there is no space left.

The Blog Summarized..

Stack is like your desk - fast, organized, limited, while Heap is like your storage room which is large and flexible. Function calls and local variables are stored in Stack and objects and complex data are stored in Heap. Stack often holds references to heap data. Stack overflow happens when stack runs out of space

just remember one thing, Stack handles execution flow. Heap stores actual data.

Once this clicks, memory stops feeling confusing — and starts feeling predictable.

The Real - Real Basics

Part 6 of 13

If you’ve ever felt like tech concepts are explained *just one layer too high*, this series is for you. **“The Real – Real Basics”** is not about definitions. It’s about **understanding what’s actually happening underneath**. Most resources jump straight into something like “This is a process”, “This is a thread” and “This is memory” But they rarely answer basic doubts like *Why do these things even exist?*, *What problem are they solving?*, *What is the computer actually doing behind the scenes?* which may arise in everyone's mind. --- ## What you’ll learn This track covers the foundations every developer *uses daily* but often doesn’t fully understand the very basic of the basics starting from *What is a Computer (beyond keyboard + screen)* to *How everything connects in real systems* --- ## Who this is for This is a supplement for *Beginners* trying to build strong fundamentals, *Developers* preparing for interviews, *Engineers* who “use things” but want to "understand them deeply" Also just to clarify these are individual blogs that can help you understand what you have already been using or would be using in you current/new role. This is not a guided course. --- ## What to expect I plan to write these blogs in a simple easy to understand language that can help connect the "layman" in us to the "coder" in us. I'll try my level best to make the blogs be with story-driven explanations, clear mental models, real backend/system relevance and no unnecessary jargon (which is very hard to do, so when I use something and any clarity is required on those, Ill try to include what that means in the blog itself and if I miss anything please let me know in comments). --- ## End goal By the end of this series, you won’t just *know* concepts, you’ll be able to **visualize them, reason about them, and use them with confidence in real systems.** --- This is where your foundation stops being *memorized* and starts becoming **intuitive**.

Up next

DNS - Domain Name System

The Internet’s “Where Do I Go?” System