Call stack behavior in Java - Time & Space Complexity
When a program runs, it keeps track of active tasks using a call stack. Understanding how this stack grows helps us see how time grows with input.
We want to know how the number of steps changes as the program calls itself or other methods.
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, where each call waits for the next.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive call to factorial with n-1
- How many times: Once per number from n down to 1, so n times
Each time we increase n by 1, the program makes one more recursive call, adding one more step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls |
| 100 | About 100 calls |
| 1000 | About 1000 calls |
Pattern observation: The number of steps grows directly with n, increasing steadily.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size n.
[X] Wrong: "Recursive calls happen all at once, so time is constant or very small."
[OK] Correct: Each call waits for the next to finish, so calls add up one after another, increasing time with n.
Understanding how the call stack grows with recursion helps you explain why some methods take longer and how to spot deep recursion in real problems.
"What if we changed the recursion to a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand call stack basics
The call stack keeps track of active method calls by adding a frame for each call.Step 2: What happens on method call
When a method is called, a new frame is pushed on top of the stack to hold its execution context.Final Answer:
It adds a new frame for the method call on top of the stack. -> Option AQuick Check:
Call stack adds frames on method calls [OK]
- Thinking call stack removes all frames on each call
- Believing variables are stored permanently in call stack
- Confusing call stack with heap memory
processData in Java?Solution
Step 1: Recall Java method call syntax
In Java, methods are called by writing the method name followed by parentheses, e.g.,processData();.Step 2: Check each option
Only processData(); uses the correct syntax without extra keywords.Final Answer:
processData(); -> Option CQuick Check:
Method call syntax = methodName() [OK]
- Adding keywords like 'call' or 'run' before method name
- Missing parentheses after method name
- Using incorrect keywords not in Java syntax
public class Test {
public static void main(String[] args) {
first();
}
static void first() {
System.out.print("A");
second();
System.out.print("B");
}
static void second() {
System.out.print("C");
}
}Solution
Step 1: Trace method calls and prints
Main callsfirst(), which prints "A", then callssecond()that prints "C".Step 2: Return to first() and print remaining output
Aftersecond()finishes,first()prints "B".Final Answer:
ACB -> Option DQuick Check:
Print order = A, C, B [OK]
- Ignoring that second() prints before first() resumes
- Assuming prints happen after all calls finish
- Mixing print order of method calls
public class Demo {
public static void main(String[] args) {
methodA();
}
static void methodA() {
methodB();
}
static void methodB() {
methodA();
}
}Solution
Step 1: Analyze method calls
methodA()callsmethodB(), which callsmethodA()again, creating a loop.Step 2: Understand call stack effect
This causes infinite recursion, adding frames endlessly until stack overflow occurs.Final Answer:
Infinite recursion causing stack overflow error. -> Option AQuick Check:
Recursive calls without base case cause stack overflow [OK]
- Thinking missing return causes syntax error
- Assuming code runs without error
- Missing the infinite recursion loop
public class StackTest {
public static void main(String[] args) {
System.out.print(factorial(3));
}
static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
}Consider how the call stack behaves during recursion.
Solution
Step 1: Understand factorial recursion
factorial(3) calls factorial(2), factorial(1), factorial(0), then returns 1.Step 2: Calculate return values on stack unwind
factorial(1) = 1 * 1 = 1, factorial(2) = 2 * 1 = 2, factorial(3) = 3 * 2 = 6.Final Answer:
6 -> Option BQuick Check:
3! = 6 by recursive multiplication [OK]
- Confusing base case return value
- Multiplying before recursive call returns
- Misunderstanding recursion order
Ready to prove it?
Pass the test and this pattern moves unknown
