The stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of a computer memory where all the variables created or initialized at runtime are stored.
They are both stored in the computer’s RAM(Random Access Memory).
In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.
An object can be stored on the stack. If you create an object inside a function without using the “new” operator then this will create and store the object on the stack, and not on the heap. Suppose we have a java class called member, for which we want to create an object, we also have a function called somefunction(). Here is what the code would look like:
Code to create an object on the stack:
Public void somefunction()
{
Member m;
}
So, the object “m” is destroyed once the function has run to completion. The memory being used for the object “m” on the stack will be removed once the function is done running.
If we want to create an object on the heap inside a function, then this is what the code would look like:
Public void somefunction(){
Member m=new Member();
}
Any data on the heap will remain there until gc manually reallocate them.
The stack is set to a fixed size, and cannot grow past its fixed size. So, if there is not enough room on the stack to handle the memory being assigned to it, a stack overflow occurs. This often happens when a lot of nested functions are being called, or if there is an infinite recursive call.
If the current size of the heap is too small to accommodate new memory, then more memory can be added to the heap by the operating system. This is one of the big differences between the heap and the stack.