KTU OOP Java2024 Scheme • 60M ESE
MODULE 2/Section 1: Polymorphism

Recursion in Java: Base Case, JVM Stack Tracing & Unwinding

HIGH PRIORITY (Prep Guide)Official Syllabus~14 min study
Official KTU 2024 Syllabus Topics Covered Here
RecursionRecursive methods and execution tracing

1. Topic Introduction

Recursion is a powerful problem-solving technique where a method breaks a problem into smaller identical subproblems by calling itself. In KTU exams, you are frequently asked to define recursion, explain what happens inside the JVM Stack during recursive calls, and trace outputs for Factorial, Fibonacci, or reverse-printing routines.

2. Start From Zero: Russian Nesting Dolls & Stack of Cafeteria Trays

Opening a Russian nesting doll reveals a smaller doll inside, until you finally hit the smallest solid doll (Base Case) that doesn't open further. Now you close them back one by one from smallest to largest (Stack Unwinding)! Every time a Java method calls itself, the JVM places a fresh tray (Stack Frame) on top of the Stack holding that call's own local variables, until the base case hits and trays pop off in reverse order.

Key Takeaway: Every valid recursive method MUST have: (1) a Base Case (if) that returns without recursing, and (2) a Recursive Step moving closer to the base case; otherwise it crashes with StackOverflowError!

3. Essential Exam Definitions

Recursion
The process of defining a solution in terms of itself; a Java method that invokes itself directly or indirectly is called a recursive method.
Base Case (Termination Condition)
An if condition inside a recursive method that returns directly without making further recursive calls, stopping infinite recursion.

4. Detailed Technical Explanation & Syntax

How the JVM Executes & Traces Recursive Methods

From your lecture notes: when a method calls itself, new local variables and parameters are allocated fresh storage on the JVM Stack inside a new stack frame, and execution starts at the top of the method with those new parameters.

When the base case returns, its stack frame is popped (removed) from the Stack, and execution resumes immediately at the exact line inside the previous call frame where the recursive call paused.

Missing Base Case Danger: If the if termination condition is omitted or never reached (e.g., fact(-1)), frames accumulate until stack memory fills, causing the JVM Error: java.lang.StackOverflowError.

5. Working Principle: Call Stack Trace of factorial(4)

  1. 1. Push fact(4): needs 4 * fact(3) -> pauses.
  2. 2. Push fact(3): needs 3 * fact(2) -> pauses.
  3. 3. Push fact(2): needs 2 * fact(1) -> pauses.
  4. 4. Push fact(1): hits Base Case (n <= 1) -> returns 1 (pops frame 4).
  5. 5. Unwind: fact(2) computes 2 * 1 = 2 -> fact(3) computes 3 * 2 = 6 -> fact(4) computes 4 * 6 = 24.

7. Complete Java Code Examples & Tracing

Factorial & Array Printing Recursion with Stack TraceRecursionTraceDemo.java
Demonstrates classic Factorial recursion plus recursive array printing from Lecture Notes, including pre-call vs post-call (unwinding) order.
1public class RecursionTraceDemo {
2 static int factorial(int n) {
3 if (n <= 1) { // Base case prevents infinite recursion
4 return 1;
5 }
6 return n * factorial(n - 1); // Recursive step
7 }
8
9 // Demonstrates order of execution during stack winding vs unwinding
10 static void printDescendingAscending(int n) {
11 if (n == 0) return;
12 System.out.print(n + " "); // Runs BEFORE recursive call (winding)
13 printDescendingAscending(n - 1);
14 System.out.print(n + " "); // Runs AFTER return (unwinding)
15 }
16
17 public static void main(String[] args) {
18 System.out.println("Factorial(5) = " + factorial(5));
19 System.out.print("Trace(3): ");
20 printDescendingAscending(3);
21 System.out.println();
22 }
23}
Expected Output
Factorial(5) = 120
Trace(3): 3 2 1 1 2 3
Keywords:staticifreturn
Common Exam & Coding Mistakes
  • Forgetting the base case if, causing StackOverflowError.
  • Calling factorial(n--) instead of factorial(n - 1) (passes original n forever before decrementing—infinite recursion!).
  • Tracing statements after the recursive call in the wrong order (forgetting LIFO stack unwinding!).

Advantages

  • Produces concise, mathematically natural solutions for trees, factorial, Fibonacci, binary search, and divide-and-conquer.

Limitations / Disadvantages

  • Consumes extra JVM Stack memory per recursive call and is slower than iteration due to method-call overhead.
  • Deep recursion risks StackOverflowError.

Real-World Applications

  • Traversing nested file directories, XML/JSON DOM trees, sorting (QuickSort, MergeSort), and backtracking solvers.

Important KTU Exam Points

  • Always trace recursive code by drawing a LIFO Stack or call tree—especially when print statements appear BOTH before and after the recursive call!
  • Explicitly mention StackOverflowError (an Error, not Exception) if base case is missing.

Memory Techniques & Revision

  • Recursion = 'Base Stop + Shrink Step + Stack LIFO Unwind'.

Common Pitfalls to Avoid

  • Writing return n * factorial(n--); — post-decrement passes n unchanged endlessly!

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Recursion is a mechanism where a method calls itself to solve smaller instances of the same problem.

  • Every recursive method requires a conditional base case (if) to stop calling itself.
  • Stack Allocation: Each recursive call creates a new stack frame on the JVM Stack containing fresh local variables and parameters.
  • Unwinding: Once the base case returns, each frame pops in LIFO order, returning values back to the calling frame.
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}

Quick Understanding Check

1. What happens at runtime if a recursive method omits its terminating if base case?