Java stack and heap memory

Pooja Nanda
CS through my eyes
Published in
1 min readDec 30, 2017

In java , two kinds of memories are used namely stack and heap memory.

Stack memory is used to store function calls and the local variables defined within the function.

Heap memory is used to store objects along with its instance values.

Let’s look at it through some code.

public class HeapStack {
int a;
public static void main(String [] args){
HeapStack obj = new HeapStack();
obj.a = 4;
}
}

In every Java application, main method is the starting point.So, first main method will be called. This will be created in Stack.As obj is a reference variable within the main function, it will be created within main.This will point to HeapStack class object created in heap memory.

Since we are creating a new object of class HeapStack type , the object will be stored in heap memory.It will have the variable ‘a’ with value 4.

This is the most simplest explanation I can give.I will add more complex examples as I understand them myself.

--

--

Pooja Nanda
CS through my eyes

CS Grad student, Computer science engineer . Likes technology , books , travelling, volunteering