Stack memory in Java - Time & Space Complexity
Let's explore how the time cost grows when using stack memory in Java programs.
We want to see how the program's steps increase as we add more function calls or data on the stack.
Analyze the time complexity of the following code snippet.
public class StackExample {
public static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
This code calculates the factorial of a number using recursion, which uses stack memory for each call.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls to factorial function.
- How many times: The function calls itself n times until it reaches the base case.
Each increase in input size adds one more function call on the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 calls |
| 10 | 10 calls |
| 100 | 100 calls |
Pattern observation: The number of steps grows directly with the input size.
Time Complexity: O(n)
This means the time to complete grows in a straight line as the input number increases.
[X] Wrong: "Recursion always makes the program slow and complex."
[OK] Correct: Recursion can be simple and efficient for problems like factorial, where each call does a small, clear step.
Understanding how stack memory affects time helps you explain recursion clearly and shows you know how function calls impact performance.
"What if we changed the recursion to a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand stack memory role
Stack memory stores data related to method execution like local variables and method calls.Step 2: Differentiate from heap memory
Heap stores objects, while stack stores method calls and local variables.Final Answer:
Method calls and local variables -> Option AQuick Check:
Stack memory = method calls + local variables [OK]
- Confusing stack with heap memory
- Thinking objects are stored in stack
- Mixing static variables with stack data
Solution
Step 1: Recall local variable syntax
Local variables inside methods are declared simply with type and name, e.g., int x = 10;Step 2: Identify invalid keywords
Keywords like 'local' or 'var int' are invalid in Java, and 'static' is not allowed for local variables.Final Answer:
int x = 10; -> Option DQuick Check:
Local variable syntax = type + name + value [OK]
- Using 'local' keyword which doesn't exist
- Trying to use 'static' inside methods
- Confusing 'var' usage in older Java versions
public class Test {
public static void main(String[] args) {
int a = 5;
int b = 10;
int c = add(a, b);
System.out.println(c);
}
public static int add(int x, int y) {
return x + y;
}
}Solution
Step 1: Trace method calls and parameters
Main calls add(5, 10), passing values 5 and 10 as local variables on the stack.Step 2: Calculate return value
Add method returns 5 + 10 = 15, which is stored in c and printed.Final Answer:
15 -> Option AQuick Check:
5 + 10 = 15 [OK]
- Concatenating numbers as strings
- Confusing method parameters with global variables
- Expecting runtime or compile errors
public class Demo {
public static void main(String[] args) {
int result = factorial(4);
System.out.println(result);
}
public static int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1);
}
}Solution
Step 1: Check recursion base case
The factorial method has a base case: if n == 0 return 1, stopping recursion.Step 2: Confirm recursion correctness
Each recursive call reduces n by 1, so recursion ends properly without stack overflow.Final Answer:
No error, code runs correctly -> Option CQuick Check:
Base case present, recursion safe [OK]
- Assuming missing base case when it exists
- Confusing local variables with stack overflow cause
- Thinking return type is wrong
public static int sum(int n) {
if (n <= 0) return 0;
else return n + sum(n - 1);
}What will happen if you call
sum(1000000) in Java, and why?Solution
Step 1: Analyze recursion depth
Calling sum(1000000) causes 1,000,000 recursive calls, each adding a stack frame.Step 2: Understand stack memory limits
Java's stack size is limited; deep recursion like this exceeds it, causing stack overflow error.Final Answer:
It will cause a stack overflow error due to deep recursion -> Option BQuick Check:
Deep recursion > stack size = stack overflow [OK]
- Assuming recursion always works regardless of depth
- Thinking it runs infinitely without base case
- Confusing runtime errors with compile errors
Ready to prove it?
Pass the test and this pattern moves unknown
