Understanding the Three Key Stacks in Java

java dev.to

Java's execution model is built around three closely related stack structures that work together whenever a method runs.

  1. JVM Stack (Thread Stack) Every thread in Java gets its own JVM stack. Responsibilities: Tracks active method calls Stores stack frames Manages method entry and return

Example:
public static void main(String[] args) {
process();
}
static void process() {
validate();
}
static void validate() {
}
While validate() is running, the stack looks like:
validate()
process()
main()
As methods return, their frames are removed from the stack.

  1. Local Variable Table

Each stack frame contains a local variable table.

static int add(int a, int b) {
int sum = a + b;
return sum;
}
Conceptually:
Slot 0 → a
Slot 1 → b
Slot 2 → sum
Stores:
Method parameters
Local variables
References to objects
The size is determined when the method is compiled, making access extremely fast.

  1. Operand Stack The JVM is a stack-based virtual machine. Most bytecode instructions operate on the operand stack. int x = 2; int y = 3; int z = x + y; Behind the scenes: push 2 push 3 add store result Execution: [] push 2 → [2] push 3 → [2, 3] add → [5] store → [] Used for: Arithmetic operations Method argument passing Intermediate results Comparisons and branching How They Work Together Consider: int result = add(10, 20); Step 1: A new frame is pushed onto the JVM stack. add() main() Step 2: Parameters are placed into the local variable table. a = 10 b = 20 Step 3: Values are loaded onto the operand stack. [10] [10, 20] [30] Step 4: The result is returned and the frame is popped. main() Quick Summary Structure Scope Purpose JVM Stack Per Thread Tracks active method calls Local Variable Table Per Stack Frame Stores parameters and local variables Operand Stack Per Stack Frame Performs bytecode operations

Source: dev.to

arrow_back Back to Tutorials