0
0
Javaprogramming~15 mins

Stack memory in Java

Choose your learning style8 modes available
menu_bookIntroduction

Stack memory helps your program keep track of what it is doing step-by-step. It stores information about method calls and local variables so your program can run smoothly.

When a method calls another method and you need to remember where to come back.
When you want to store temporary data like local variables inside a method.
When you use recursion and need to keep track of each recursive call.
When you want to understand how your program uses memory during execution.
When debugging to see the order of method calls and variable values.
regular_expressionSyntax
Java
public class StackMemoryExample {
    public static void main(String[] args) {
        int number = 5; // stored in stack
        int result = factorial(number); // method call stored in stack
        System.out.println("Factorial of " + number + " is " + result);
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1; // base case
        } else {
            return n * factorial(n - 1); // recursive call
        }
    }
}

Each method call creates a new stack frame that holds its local variables and return address.

Stack memory is limited in size and follows Last In First Out (LIFO) order.

emoji_objectsExamples
line_end_arrow_notchThis example shows simple method calls and local variables stored in stack memory.
Java
public class StackMemoryExample {
    public static void main(String[] args) {
        int a = 10; // stored in stack
        int b = 20; // stored in stack
        int sum = add(a, b); // method call stored in stack
        System.out.println("Sum: " + sum);
    }

    public static int add(int x, int y) {
        return x + y;
    }
}
line_end_arrow_notchThis example shows recursion where each call adds a new frame to the stack until the base case is reached.
Java
public class StackMemoryExample {
    public static void main(String[] args) {
        int number = 3;
        int result = factorial(number);
        System.out.println("Factorial: " + result);
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}
line_end_arrow_notchWhen the program starts, the main method's stack frame is created. If it does nothing, the stack frame is still created and removed when main ends.
Java
public class StackMemoryExample {
    public static void main(String[] args) {
        // Empty main method
    }
}
code_blocksSample Program

This program calculates the factorial of a number using recursion. Each recursive call uses stack memory to store its own local variable 'n' and return address. When the base case is reached, the calls return one by one, freeing stack frames.

Java
public class StackMemoryDemo {
    public static void main(String[] args) {
        System.out.println("Program started");
        int number = 4;
        System.out.println("Calculating factorial of " + number);
        int factorialResult = factorial(number);
        System.out.println("Factorial of " + number + " is " + factorialResult);
        System.out.println("Program ended");
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Time complexity of recursive factorial is O(n) because it calls itself n times.

line_end_arrow_notch

Stack memory size is limited; too many recursive calls can cause a StackOverflowError.

line_end_arrow_notch

Common mistake: forgetting the base case in recursion causes infinite calls and stack overflow.

line_end_arrow_notch

Use stack memory for temporary data and method calls; use heap memory for objects that live longer.

list_alt_checkSummary

Stack memory stores method calls and local variables in a Last In First Out order.

Each method call creates a new stack frame that is removed when the method finishes.

Recursion uses stack memory heavily, so always have a base case to avoid errors.