Factorial of a Number using Command Line Arguments in Java

Introduction

In this post, I am going to write a program to find factorial of a number using command line arguments in java.

Also Read: Print 1 to 50 using do-while loop in Java

Command line arguments are the arguments that we pass to the main program at the time of execution.

It is not necessary to pass arguments at the time of execution. But there are some occasions where we need to supply the arguments at run time.

Before writing the program, let us see the expected output.

Expected Output

factorial of a number using command line arguments in java

In the first line, I am compiling the java program.

In the second line, I am simply running the java program by typing the command

We are not supplying any argument here. But, in our program, exception will be there. Why? Because whatever arguments we are supplying from this command line, it will be stored in args array in the form of string. Where is args?

Also Read: Java Program to Find Whether a Person is Eligible to Vote or Not

In the main class, there is a main function i.e. public static void main(String args[ ]). Here is the args array. First argument will be stored at args[0], second at args[1] and so on. These array values will be used in the main program.

Therefore, we are getting an exception i.e. run time error here.

Now, see the other command.

Here, we are passing the value 5 to the main program and this value will be stored at args[0] in the form of string. Next, we will convert that value into integer using parseInt() method.

Now, see the actual program.

Factorial of a Number using Command Line Arguments in Java

class Factorial
{
    public static void main(String args[])
    {
         int n, fact = 1, i = 0;
         try
         {
             n = Integer.parseInt(args[0]);
             for(i=1; i<=n; i++)
             {
                 fact = fact * i;
             }
            System.out.println("Factorial of "+n+" is "+fact);
         }
         catch(Exception e)
         {
            System.out.println(e);
         }
    }
}

As I said above, if I don’t pass any argument, then we will get an exception. For this, I have used try catch statement to handle exceptions.

Also Read: Sum of Odd and Even Digits in a Number in Java

I hope you have understood this program. If you have any difficulty, then feel free to contact me.

Thank you.

Leave a Comment