• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Factorial Program in Java [While Loop | For Loop | Do While Loop | Recursion]

February 25, 2019 by javainterviewpoint Leave a Comment

The factorial of n numbers can be denoted as n!, it is the product of all number less than or equal to n

n! = 1 * 2 * 3* . . . . (n-2) * (n-1) * n

In this article, we will create the Factorial Program in Java using the below 4 ways

  • Using For loop
  • Using While loop
  • Using Do While loop
  • Using Recursion

Factorial Program In Java

Example 1: Factorial Program in Java using For loop

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = 1;

        for (int i = 1; i <= number; i++)
        {
            factorial = factorial * i;
        }
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

In the above code, we used a for loop to iterate through the numbers 1 to the given number [6] and during each iterations product is saved to the factorial variable.

Example 2: Factorial Program in Java using While loop

package com.javainterviewpoint;

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = 1;
        int i=1;
        
        while (i <= number)
        {
            factorial = factorial * i;
            i++;
        }
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

The above code is almost the same, instead of a for loop we are using the while loop and the loop incrementation happens inside the body of the loop (i++)

Example 3: Factorial Program in Java using Do While loop

package com.javainterviewpoint;

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = 1;
        int i = 1;
        
        do
        {
            factorial = factorial * i;
            i++;
        } while (i <= number);

        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

The difference between while loop and do while loop is that, in while loop the condition is checked at the beginning of each iteration and in do while loop the condition is checked at end of each iteration

Example 4: Factorial Program in Java using Recursion

package com.javainterviewpoint;

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = calculateFactorial(number);

        System.out.println("Factorial of " + number + " is: " + factorial);
    }
    
    public static long calculateFactorial(int number)
    {
        if (number == 1)
            return 1;
        else
            return number * calculateFactorial(number -1);
    }
}

In the above code, we will be passing the number to the calculateFactorial() method, till the number is greater than 1 then the number is multiplied with calculateFactorial() recursively where number -1 is passed to it.

Example 5: Factorial Program in Java using Scanner

package com.javainterviewpoint;

import java.util.Scanner;

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = 1;
        
        Scanner scanner= new Scanner(System.in);

        System.out.println("Enter the Number : ");

        number = scanner.nextInt();

        for (int i = 1; i <= number; i++)
        {
            factorial = factorial * i;
        }
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Scanner is a class in java.util package, it can be used to read input from the keyboard. We will be getting the input the from the user for which the factorial needs to be calculated and factorial is calculated using for loop.

Output:

Enter the Number : 
5
Factorial of 5 is: 120

Example 6: Factorial Program in Java using Command Line Arguments

package com.javainterviewpoint;

public class FactorialProgram
{
    public static void main(String[] args)
    {
        int number = 6;
        long factorial = 1;
        
        number = Integer.parseInt(args[0]);

        for (int i = 1; i <= number; i++)
        {
            factorial = factorial * i;
        }
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output :

Run the program passing the command line argument “java Factorial Program 6”

If you are using eclipse IDE then follow the below steps to pass command line argument

  • Click on Run -> Run Configurations
  • Click on Arguments tab
  • In Program Arguments section , Enter your arguments.
  • Click Apply

Other interesting articles which you may like …

  • Java Program to Print Floyd’s Triangle
  • 33 Number Pattern Programs In Java
  • 23 Alphabet Pattern Programs in Java
  • Sort Objects in a ArrayList using Java Comparator
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Difference between equals() and ==
  • Difference Between Interface and Abstract Class in Java
  • Difference between fail-fast and fail-safe Iterator
  • Difference between Enumeration and Iterator ?
  • Difference between HashMap and Hashtable | HashMap Vs Hashtable
  • Java StringTokenizer Example
  • How to Reverse String in Java using String Tokenizer
  • What is the use of a Private Constructors in Java
  • Fibonacci Series Java Example
  • For Loop in Java with Example
  • For-each loop or Enhanced For loop in Java
  • Use of Class.forName in java
  • why we Use Class.forName in SQL JDBC
  • Can we Overload static methods in Java

Filed Under: Java, Java Program Tagged With: Do while loop, Factorial, Factorial Program, Factorial Program in Java, For Loop, Java Program, Recursion, While Loop

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·