Web | This Site

Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Java Examples - Calculating Factorial

## Problem Description:

How to use method for calculating Factorial of a number?

## Solution:

This example shows the way of using method for calculating Factorial of 9(nine) numbers.

    public class MainClass {
       public static void main(String args[]) {
          for (int counter = 0; counter <= 10; counter++){
             System.out.printf("%d! = %d\n", counter,
             factorial(counter));
          }
       }
       public static long factorial(long number) {
          if (number <= 1)
             return 1;
          else
             return number * factorial(number - 1);
       }
    }

## Result:

The above code sample will produce the following result.

    0! = 1
    1! = 1
    2! = 2
    3! = 6
    4! = 24
    5! = 120
    6! = 720
    7! = 5040
    8! = 40320
    9! = 362880
    10! = 3628800

Advertisement

Online Image Processing

Indian Baby Names