Factorial of a non negative integer in Java

Posted By: Java Examples - 4:29 PM


& Comment

Description of this program :
This Java programming 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 util package. Java util package has a Scanner is used for reading the input . 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<=x and i++ as increment operator. So output result will be like fact=fact*i.
Java version of this program is given bellow :

package power;

import java.util.Scanner;

 * @author ACHCHUTHAN
public class Factorial {

    int x;

    public Factorial() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the Factorial Number :");
        x = input.nextInt();


    public int getX() {
        return x;

    public int getFact() {
        if (x == 0) {
            return 1;
        } else {
            int fact = 1;
            for (int i = 1; i <= x; i++) {
                fact = fact * i;

            return fact;


    public static void main(String args[]) {
        Factorial a = new Factorial();
        System.out.println(a.getX() + " " + "Factorial is = " + a.getFact());


Output of this program :

Enter the Factorial Number :
10 Factorial is = 3628800
BUILD SUCCESSFUL (total time: 3 seconds)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.


Post a Comment

Thank you for vising Java90.blogspot.com

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .