Website For Developers

Recursive method in Java



Example recursive factorial method in Java

import java.util.Scanner;

class Factorial {

   public static void main(String args[]) {
     //Getting User Input
     Scanner scan = new Scanner(System.in);
     System.out.println( "Please enter a number for factorial" );
     int number = scan.nextInt();
     System.out.println(factorial_method(number));
   }

   public static int factorial_method (int num) {
     if (num <= 0) {
       return 1;
     }
     else {
       // Recursive call
       return num * factorial_method(num-1);
     }
   }
}


Output

Please enter a number for factorial
6
720