Home Java Javatutorial Factorial Program in Java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Factorial Program in Java

Advertisement
Factorial program in Java helps programmer to write factors of any given integer number. In the following example, a class by the name 'Factorial1' is used. BufferReader is defined under the Java I/O package. System.in is used to take the input from system/user at run time. InputStreamReader reads the input from user and then keep it into a buffer.

Factorial program in Java helps programmer to write factors of any given integer number. In the following example, a class by the name "Factorial1" is used.

'try' and 'catch' block are used for catching and handling exceptions during execution of the program.

BufferReader is defined under the Java I/O package. System.in is used to take the input from system/user at run time. InputStreamReader reads the input from user and then keep it into a buffer. As Java reads all the input in the form of String so, here we will have to parse the String input into the integer. For this we will use parseInt() method of Integer class that is used to convert the strings into integers.

If the input is out of the array than the program will display the result as "Array out of bounds exception".

Example of Factorial program in Java:

import java.io.*; 

class Factorial1{
  public static void main(String[] args) {
  try{
  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++){
  fact=fact*i;
  }
  System.out.println(fact);
  }
  catch (Exception e){
  System.out.println("Array out of bounds exception");
  }
  }
}

Output

C:\Documents and Settings\bharat\Desktop\bipul\CoreJava\Swing Example\Factorial>
javac Factorial1.java

C:\Documents and Settings\bharat\Desktop\bipul\CoreJava\Swing Example\Factorial>
java Factorial1
enter the number
5
Factorial of 5:

120.0

Advertisements

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: May 3, 2013

Related Tutorials

Ask Questions?    Discuss: Factorial Program in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com