← Back to Chapters

Java Recursion

? Java Recursion

? Quick Overview

Recursion in Java is a programming technique where a method calls itself to solve a problem by breaking it into smaller subproblems. Each recursive call works on a reduced version of the original problem until a base condition is met.

? Key Concepts

  • Recursive method must call itself
  • Every recursion must have a base condition
  • Each call uses stack memory
  • Problem is divided into smaller subproblems

? Syntax / Theory

A recursive method in Java consists of two essential parts:

  • Base Case: Condition to stop recursion
  • Recursive Case: Method calling itself
? View Code Example
// Recursive method syntax in Java
returnType methodName(parameters) {
// base condition
if(condition) {
return value;
}
// recursive call
return methodName(modifiedParameters);
}

? Code Example(s)

? View Code Example
// Java program to calculate factorial using recursion
class Factorial {
static int factorial(int n) {
// base condition to stop recursion
if(n == 0) {
return 1;
}
// recursive call
return n * factorial(n - 1);
}

public static void main(String[] args) {
int result = factorial(5);
System.out.println(result);
}
}

? Live Output / Explanation

Output

120

The method keeps calling itself by reducing the value of n until it reaches 0. Once the base case is reached, values are returned step-by-step to compute the final result.

?️ Interactive Demo: The Call Stack

Visualize how the Stack Frame builds up and unwinds during recursion.

Stack is empty
Ready to run...

✅ Tips & Best Practices

  • Always define a clear base condition
  • Keep recursive calls minimal
  • Avoid deep recursion to prevent stack overflow
  • Use iteration if recursion affects performance

? Try It Yourself

  • Write a recursive program to calculate Fibonacci numbers
  • Create a recursive method to find sum of digits
  • Implement recursion to reverse a number