Recursion In JAVA | Core Java Tutorial | Minigranth

Recursion In Java : Introduction

  • Recursion is supported in Java. A method calling itself is called recursion.
  • In simple terms we can say that when a method body contains a calling statements for itself.
  • Recursive methods has two parts :
    • Base case : A base case is required to terminate a recursive process, else it will run infinitely.
    • Self-call statement : A self-calling statement is present is recursive method body, which always tends to base case i.e. every time a recursive method calls itself it approaches to base case .

Recursion In Java : Example

  • Let’s take an example where we will find a factorial of a number using recursion.
This image describes a sample program of recursion in java.
Recursion In Java : Example

This image describes the output of the sample program for recursion in java.
Recursion In Java : Output

Recursion In Java : Working

This image describes the flowchart of recursion in java.
Recursion In Java : Flowchart
  • As x=0 it returns 1 to the method it was called from and it starts backtracking to get the final results as 120.

  • Note : Every time a method is called a new memory area is created.