Video in progress

What is inside a stack frame when a method is called?

Each call opens a new frame: it holds an array of local variables, an operand stack and a reference to the constant pool. When the method returns, the frame is removed entirely.

📖 Answer

Say main -> process -> calculate are being called. Three frames sit on top of each other on the thread's stack, with calculate at the top.

Inside each frame:

  • the local variables array: this (slot 0 in an instance method), parameters, variables declared in the method. long and double take two slots;
  • the operand stack: the temporary stack bytecode uses for calculations (iadd takes two numbers and pushes the result);
  • a constant pool reference: for finding methods and fields;
  • return information: where to go back to.

The size of a frame is known at compile time (max_locals, max_stack), so opening a frame is very cheap.

When an exception is thrown, the JVM unwinds the frames one by one looking for a matching catch. A stack trace is exactly the list of these frames.