Factorial of a number in Java using while loop

In this post we tackle a simple problem of calculating the factorial of a number. Specifically, we determine Factorial of a number in Java using while loop.

Factorial of a number in Java using while loop

So this will be a single loop to calculate the factorial value we want:
/**
 * An example program that computes the Factorial of a number in Java using while loop.
 */
public class ExampleProgram {
    public static void main(String[] args) {
        System.out.println(5 + " factorial = " + factorial(5));
        System.out.println(7 + " factorial = " + factorial(7));
        System.out.println(9 + " factorial = " + factorial(9));
        System.out.println(11 + " factorial = " + factorial(11));
    }
    public static int factorial(int n) {
        int f = n;
        while (n>1) {
            f = f * (n-1);
            n--;
        }
        return f;
    }
}

And we get below output when we run the code above:

5 factorial = 120
7 factorial = 5040
9 factorial = 362880
11 factorial = 39916800