Print factorials for any given number

In this example we are going to write a java class which will enable us to print factorial for any given number.
A quick refresher: 
  • The factorial of 0 and 1 is always 1.
  • Formula to find a factorial is: n! = n*(n-1)!
  • Exp: 5 = 5*4*3*2*1 = 120

import java.util.Scanner;

public class PrintFactorials {

    public int factorials() {
        int factorial = 1;
        int input;
        System.out.print("Please enter any integer value. ");
        Scanner scanner = new Scanner(;
        input = scanner.nextInt();

        if (input < 0)
            .println("The entered number is not positive!!! Please re-try...");
        else {
            for (int counter = 1; counter <= input; counter++)
                factorial = counter * factorial;
            .println("The factorial of " + input + " is " + factorial);
        return factorial;

    public static void main(String[] args) {

        PrintFactorials pf = new PrintFactorials();


Please enter any integer value. 5
The factorial of 5 is 120

1 comment:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.