Stack Memory

Stack Memory Usage in Method Execution
Example: How Stack Works
Execution Flow in Stack Memory
main()method starts → Pushes stack frame formain().add(5,3)is called → A new stack frame foradd()is created.Local variables (
a,b,sum) stored in stack frame.Method
add()returns → Stack frame foradd()is removed.Execution returns to
main(), and finally, the stack frame formain()is removed after execution completes.
Key Stack Memory Operations
1. Method Call Handling
Each method call creates a new stack frame.
After execution, the frame is popped from the stack.
JVM uses the return address stored in the frame to resume execution.
2. Local Variable Storage
Primitive variables (int, float, double, char, boolean) are stored directly in stack memory.
Object references are stored in stack, but the actual object is in heap memory.
Example: Primitive vs Object Reference in Stack
Variable Type
Stored In
Primitive (int, char, float, etc.)
Stack Memory
Reference Variables
Stack Memory (only reference)
Actual Objects (String, Array, etc.)
Heap Memory
Stack Memory Management
Stack Memory Allocation
Stack memory size is fixed per thread and can be adjusted using:
Each thread gets its own separate stack.
Stack Memory Deallocation
Automatic deallocation when a method completes execution.
No need for Garbage Collection.
Common Stack Memory Issues
1. StackOverflowError (Infinite Recursion)
If the stack limit is exceeded, JVM throws a StackOverflowError. This happens with deep recursion or excessive method calls.
Example: StackOverflowError (Infinite Recursion)
2. Large Local Variables & Deep Recursion
Large arrays or deep recursion can consume stack memory quickly.
Use iterative approaches instead of recursion.
Example: Large Local Variable Consuming Stack
Last updated