Heap vs Stack Memory

Program’s memory allocation is done on the Heap and the Stack.

For example if we declare a variable like below, it would be on the stack

int i = 10;

Objects can also be found on the stack when declared and set like so:

myobject obj = null;

When an object is declared but not set to a variable, it will only be found on the heap. For example:

new myobject();

The above is not on the stack yet as it hasnt been set. The Stack contains locally set variables. So combining the examples above the variable “obj” will be found on the Stack and will have a memory reference to the myobject object that was created on the Heap.

myobject obj;
obj = new myobject();

Finally, from the above example if we reset the “obj” variable to null, then the Heap will still contain the instantiated myobject. Later, the Java Garage Collector will go through and clear out the Heap memory.

myobject obj; 
obj = new myobject();
obj = null;