Java Program to find factorial of a number

We have previously listed core java written interview questions. Sometimes interviewer asked you to write a program to find the factorial value of a given number. So In this post, I am simply creating a program to calculate the factorial of given number using a recursion function, about recursion function we separately post a tutorial.

FactorialExample.java
package com.javamakeuse.poc;

public class FactorialExample {

 // recursion method to calculate factorial
 // ex. !5 = 5*4*3*2*1
 public static int findFactorial(int num) {
  if (num < 1) {
   throw new IllegalArgumentException("Not a valid number");
  } else if (num == 1) {
   return 1;
  } else {
   return num * findFactorial(num - 1);
  }
 }
 public static void main(String[] args) {
  System.out.println("Factorial of given number is - " + findFactorial(5));
 }
}

OUT PUT:
Factorial of given number is - 120


Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions