Calculate factorial using recursion in Java

package com.w3mentor.examples.factorial; 
 
public class Factorial { 
 
  int calculate(int number) { 
    if (number < 0) { 
      throw new IllegalArgumentException("integer must be greater than zero"); 
    } 
    if( number == 0) {      return 1; 
    } else { 
      return number * calculate (number - 1); 
    } 
  } 
 
  public static void main(String[] args) { 
    Factorial factorial = new Factorial(); 
    System.out.println(factorial.calculate(5)); 
  } 
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.