Factorial Program in Java

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

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


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