Skip to Content

Java Factorial Example

  1. /*
  2.   Java Factorial Example
  3.   This Java Factorial Example shows how to calculate factorial of
  4.   a given number using Java.
  5. */
  6.  
  7. public class NumberFactorial {
  8.  
  9.         public static void main(String[] args) {
  10.                
  11.                 int number = 5;
  12.                
  13.                 /*
  14.                  * Factorial of any number is !n.
  15.                  * For example, factorial of 4 is 4*3*2*1.
  16.                 */
  17.                
  18.                 int factorial = number;
  19.                
  20.                 for(int i =(number - 1); i > 1; i--)
  21.                 {
  22.                         factorial = factorial * i;
  23.                 }
  24.        
  25.                 System.out.println("Factorial of a number is " + factorial);
  26.         }
  27. }
  28.  
  29. /*
  30. Output of the Factorial program would be
  31. Factorial of a number is 120
  32. */