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.
Stack memory in 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.
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; } }
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); } } }
public class StackMemoryExample { public static void main(String[] args) { // Empty main method } }
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.
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); } } }
Time complexity of recursive factorial is O(n) because it calls itself n times.
Stack memory size is limited; too many recursive calls can cause a StackOverflowError.
Common mistake: forgetting the base case in recursion causes infinite calls and stack overflow.
Use stack memory for temporary data and method calls; use heap memory for objects that live longer.
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.
