Factorial Sample Code In Java Using Recursion

 Posted On  | Yashwant Chavan 

Today we are going to learn on Java recursion. We are going to calculate Factorial of given number using java recursion program. Before that we need to learn what is recursion ? Recursion is nothing but calling method itself, Its endless looping method calling till method stack is overflow or explode. To avoid this you need to define the exit point or exit condition , where method stop its recursion calling.

Factorial using Recursion

In the below example , we are going to calculate factorial of the number. But before that we need to know what is factorial ? e.g. If you want to calculate factorial of 5 , then its factorial value is (5*4*3*2*1) = 120.

package com.technicalkeeda.app;

public class FactorialRecursionExample {
    public static void main(String[] args) {
        int number = new FactorialRecursionExample().calculateFactorial(5);
        System.out.println(number);
    }

    public int calculateFactorial(int number) {
        int returnValue;

        if (number == 1) {
            return 1;
        }

        returnValue = calculateFactorial(number - 1) * number;

        return returnValue;

    }
}

Recursion Explanation

calculateFactorial() method executed as in below manner. Recursion is highlighted with step by step execution.

-> calculateFactorial(5)  // first call
  -> calculateFactorial(4)
    -> calculateFactorial(3)
      -> calculateFactorial(2)
        -> calculateFactorial(1) - stop condition
 <- 1
      <- 1 = 1 * 1 // stack unwinding and return the value, to caller method  
    <- 2 = 2 * 1
  <- 6 = 3 * 2
<- 24 = 4 * 6
<- 120 = 5 * 24  // final output value


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0310 seconds.