Java Stack and Heap: Java Memory Allocation Tutorial
What is Stack Memory?
Stack in java is a section of memory which contains methods, local variables, and reference variables. Stack memory is always referenced in Last-In-First-Out order. Local variables are created in the stack.
Heap is a section of memory which contains Objects and may also contain reference variables. Instance variables are created in the heap
Memory Allocation in Java
The JVM divided the memory into following sections.
Difference between Stack and Heap
Let’s take an example to understand this better.
Consider that your main method calling method m1
The statement new Account() will create an object of account in heap.
The reference variable “ref” will be created in a stack java.
The assignment “=” operator will make a reference variable to point to the object in the Heap.
Once the method has completed its execution. The flow of control will go back to the calling method. Which in this case is method m2.
The stack from method m3 will be flushed out.
Since the reference variable will no longer be pointing to the object in the heap, it would be eligible for garbage collection.
Once method m2 has completed its execution. It will be popped out of the stack, and all its variable will be flushed and no longer be available for use.
Likewise for method m1.
Eventually, the flow of control will return to the start point of the program. Which usually, is the “main” method.
What if Object has a reference as its instance variable?