Memory in Programming — Stack vs Heap
Your Desk vs Your Storage Room

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 formain. The variableresultis 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 parametersa = 2,b = 3stored in stackStep 3: Inside
add()method the valuesum = 5stored in stackStep 4: The
add()stack frame is removed and5is returned tomainStep 5: Back in
main()the variableresultis set to5
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 formain.Step 2: The reference
pis stored in stack and the objectnew Person()is created in heapStep 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.






