The memory management is done in Stack and Heap in java. whenever the java command is triggered it divides memory in two parts(Stack and Heap) for the program, the Stack is used for the execution purpose and Heap is used for the storage purpose.
Heap memory is used to allocate memory to Objects created in java at runtime. Whenever the object is created it is always created in heap. Heap memory can be used in all parts of the program.
Stack memory execution is always done in Last-In-First-Out(LIFO) manner. Stack is used one by one by the threads only.The Stack memory contains the reference of the object created in the Heap.
Here is the steps involved in allocation of memory.
Step 1 :
whenever the java command gets hit its execution is done in the stack memory first. It always check first whether the java class is loaded in heap memory or not. If not, it loads the java class.
Step 2 :
An object is created in the heap memory which is the Class Memory. Afterwards all static members are loaded. Then main() method is called for execution purpose as execution of all java programs is always start with main() method.
Step 3 :
main() method enters stack memory for execution. First main() method is executed.Then other Methods of main() get executed.
Step 4 :
After the execution one by one control comes back to main() method. main() is already executed. So if there are no other statements for the execution then execution leaves the stack memory.
Step 5 :
Java command also leaves stack memory leaving allocated memory for the OS memory.