Skip to content
C

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.


1. What 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.

2. Why 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.

3. Real-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.

4. Syntax

java
// Not directly written in code - managed automatically by the JVM void methodA() { int x = 10; // stored in methodA's stack frame methodB(); }

5. Example Program

java
public 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

6. Key Points to Remember

  • Each thread in Java gets its own separate Stack.
  • Stack memory is automatically managed — memory is freed as soon as a method call finishes.
  • Excessive recursive method calls can exhaust Stack memory, causing a StackOverflowError.