Home Java Beginners Write a program to calculate factorial of any given number


Share on Google+Share on Google+

Write a program to calculate factorial of any given number

This tutorial will teach you the methods for writing program to calculate factorial of any given number.

Factorial Examples - Java Factorial Example to calculate factorial of any given number


This Java programming tutorial will teach you the methods for writing program to calculate factorial of any given number. First of all define a class "Factorial" under the Java I/O package. Java I/O package has a input stream and a output stream in which input stream is used for reading the stream and memory allocating and the output stream is used for writing bytes. As in this program we are going to insert certain instruction by creating buffer reader class, it is necessary to use 'try' and 'catch' block for catching and handling exceptions during execution of the program.  

Here, we have to create a buffer for the string class that can be used to instantiate a changeable object for storing and processing a string of character. The strings length and content change as soon as any object is inserted, replaced or removed from the StringBuffer object. 

Now create a buffer object that inherits properties from the string object class. Now create an InputStreamReader that reads bytes and decodes them into character by using certain 'charset'. Now use the ParseInt method for converting the parses the string argument to a decimal integer and define 'a' as an integer. Take an integer variable as fact=1 and insert the message in the System method. 

Now applying for loop with conditions as integer i=1(intializer),  i<=a and i++ as increment operator. So output result will be like fact=fact*i.

Here is the code of the program:

import java.io.*; 
class Factorial{
  public static void main(String[] args) {
  BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("enter the number");
  int a= Integer.parseInt(object.readLine());
  int fact= 1;
  System.out.println("Factorial of " +a+ ":");
  for (int i= 1; i<=a; i++){
  catch (Exception e){}

Download this example.

Updated Example description

This is the updated example of factorial that will evaluates the factorial of number in double which is lies in the range of double data type in java.

Here is the code of program:

import java.io.*; 

class Factorial1{
  public static void main(String[] args) {
  BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
  System.out.println("enter the number");
  int a= Integer.parseInt(object.readLine());
  double fact= 1;
  System.out.println("Factorial of " +a+ ":");
  for (int i= 1; i<=a; i++){
  catch (Exception e){
  System.out.println("Array out of bounds exaception");



Download this example.



If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 4, 2007

Related Tutorials

Ask Questions?    Discuss: Write a program to calculate factorial of any given number   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Israel Wondimu
April 16, 2011
Thank you!!

tasreef khan
April 19, 2011

what is BufferedReader and parseIntin in the program and what use these in the program.
April 21, 2011

I want to calculate factorial 256!. How can I do it & how can I display the result.
May 26, 2011
java basic programs

please forward me java basic programs which are mstly asked in interviews
June 28, 2011
java and c++

is good
July 4, 2011

how to factor at my age of 17..
July 29, 2011

July 29, 2011
logic and programming

thank you!!!
August 22, 2011

i need help for calculating the factorial and triangular of a given number.
August 22, 2011
worked like a charm

thanks, it worked like a charm, very helpful. :)
jim rae
September 29, 2011

E Factorial Divisibility selected by Joe Horton The number (n!) is de ned to be the product of the n smallest positive integers. Thus 4! = 1 × 2 × 3 × 4. We want to know how many times you can divide 2 into (n!). Since 2 divides 12 once, and 2 divides 4 twice, but does not divide 3 at all, the number of times 2 divides (4!) is exactly three. Write a program to determine the number of times n! is divisible by 2. Input A sequence of positive integers all on one line, separated by spaces, and followed by 0. Output For each input integer n, excluding the last zero, print out a line: ”n factorial is divisible by exactly k 2’s.” Sample input 5 7 2 0 Output should be: 5 factorial is divisible by exactly 3 twos. 7 factorial is divisible by exactly 4 twos. 2 factorial is divisible by exactly 1 twos. (Ignor the bad grammar in the special case when the number of twos is 1.)
October 22, 2011

public static String inString(String prompt) { inputFlush(); printPrompt(prompt); return inString(); } public static String inString() { int aChar; String s = ""; boolean finished = false; while (!finished) { try { aChar = System.in.read(); if (aChar < 0 || (char) aChar == '\n') finished = true; else if ((char) aChar != '\r') s = s + (char) aChar; // Enter into string } catch (java.io.IOException e) { System.out.println("Input error"); finished = true; } } return s; } public static int inInt(String prompt) { while (true) { inputFlush(); printPrompt(prompt); try { return Integer.valueOf(inString().trim()).intValue(); } catch (NumberFormatException e) { System.out.println("Invalid input. Not an integer"); } } } public static char inChar(String prompt) { int aChar = 0; inputFlush(); printPrompt(prompt); try { aChar = System.in.read(); } catch (java.io.IOException e) { System.out.println("Input error"); } inputFlush(); return (char) aChar; } public static double inDouble(String prompt) { while (true) { inputFlush(); printPrompt(prompt); try { return Double.valueOf(inString().trim()).doubleValue(); } catch (NumberFormatException e) { System.out .println("Invalid input. Not a floating point number"); } } } }
October 27, 2011
regarding java

nothing u are good enough to handle expectional handling
yathartha sharma
November 28, 2011
java technology

this is such a nice site and thanks for the answer
December 24, 2011
send me same basics of java

it was gud to refer
January 4, 2012

very hard :P
January 10, 2012
how to find sum of series of factorial values

write a program to calculate & print the result of following series 1!+2!+3!+ . . . . . .+n! here n is any given number.
January 15, 2013

what is recursion and input factorial in java programing
Hassan Irgui
January 26, 2012
Formula is off by 1

I am just a beginner in Java programming. I looked up your int code for the factorial and compared it to an excel sheet output. I looks like your coding is missing the fact that the system will always start at zero even if your loop says i=1. With you code, the factorial of 5 for example is 24 whereas the real factorial of 5 is 120! Here is my fix for this bug. for (int i= 1; i<=a+1; i++){ fact=fact*i; adding the 1 to a (a+1) corrects the loop and gives an accurate output. Have a great day. Hassan/Canada
Orlan Villarino
March 23, 2012
java script

How to run a program that include on how to block a number
March 23, 2012

What do the keywords "try" and "catch" mean in the code?
July 24, 2012
I need one more clarrification

Thks for posting.. useful example for begineers . i have one doubt why u given "Array out of bounds exception" if the input is double value?? does we can do with double Value??
August 21, 2012

Hi, im a begginner, so how do i run it?
September 12, 2012

java is best subject
September 16, 2012
this is correct one

this is correct: fact=fact*a;
ranjeet kumar
October 11, 2012
java swing

sir, how to display 12 month calendar structure format in frame when i enter year,i only want its interface code plzs suggest me
November 15, 2012
the dificulty of java

this program gave me cancer
November 16, 2012
hevlo everyone :)

i0 want to know more about this java programming
tahrir kilafah
May 2, 2013
computer since

how i can make database
Nithin joseph
August 16, 2013

factorial system definde program
Nithin joseph
August 16, 2013

factoriyal program all?