JVM Internals & Memory · Lesson 119 of 150
Stack
The Stack is a memory area used to store method calls and their local variables. Each time a method is called, a new block (called a stack frame) is added; when the method finishes, that block is removed.
01What is the Stack (in JVM memory)?
The Stack is a memory area used to store method calls and their local variables. Each time a method is called, a new block (called a stack frame) is added; when the method finishes, that block is removed.
02Why is it used?
The Stack keeps track of exactly where a program is during method execution, including local variables and the order in which methods must return, allowing correct and organized execution of nested method calls.
03Real-Life Example
Think of a stack of plates in a cafeteria. The last plate placed on top is the first one picked up. Similarly, the most recently called method's data is stored on top of the Stack, and it's removed first once that method completes.
04Syntax
java// Not directly written in code - managed automatically by the JVM void methodA() { int x = 10; // stored in methodA's stack frame methodB(); }
05Example Program
javapublic class StackDemo { static void methodB() { System.out.println("Inside methodB"); } static void methodA() { System.out.println("Inside methodA"); methodB(); } public static void main(String[] args) { methodA(); } }
Output:
Inside methodA
Inside methodB