View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Command Line Arguments in Java [With Example]

By Rohan Vats

Updated on Jul 03, 2023 | 7 min read | 7.3k views

Share:

While writing your Java programs, you must have noticed the (String[] args) in the main() method. These are command-line arguments being stored in the string passed to the main method. These arguments are called command-line arguments.

It is quite common to use command-line arguments because you don’t want your application to do the same thing in every run. If we want to configure its behaviour somehow, we will have to use command-line arguments.

Check out our free courses to get an edge over the competition

A Few Facts to Keep in Mind about Command Line Arguments in Java

Before understanding the use of Java program command line arguments, let’s quickly evaluate the most important facts in the following points:

  • You can use command-line arguments to specify any configuration information while launching the Java application
  • You can use multiple arguments in the command line simultaneously without any limitations
  • Command-line arguments have data that come in the form of string

What is the Use of Command-Line Arguments?

These command-line arguments are passed from the console. They can be received in the java program to be used as input. We can pass as many arguments as we want, as it is stored in an array. Here is an example of how you can use the command line arguments.

In the program

class test
{
    public static void main(String[] args)
    {
        for(int i=0;i< args.length;++i)
        {
            System.out.println(args[i]);
        }
    }
}

 

Check out upGrad’s Advanced Certification in Blockchain\

A Brief on Java Code to Understand Command-Line Arguments

Do you want to understand the command line input in Java? Then, you first need to create a file: CommandLine.java. There, write the code (as mentioned below) to display the arguments that pass via the command line:

//Display all command-line arguments.
class CommandLine
{
public static void main(String args[ ])
{
        System.out.println(“The command-line arguments are:\n”);
     for (int x = 0; x < args.length; x++)
            System.out.println("args[" + x + "]: " + args[ x ]);
}
}

 

How to Run the Program

You must follow a few steps to compile and run the Java program in the command prompt. Here’s a list of steps to follow:

  • First, save this program as the CommandLine.java
  • Now, open the command prompt window, and there, compile this program- javac CommandLine.java
  • After you have completed compiling it successfully, you now need to run the command by writing arguments- java CommandLine argument-list (for instance – java CommandLine upGrad Java Tutorial)
  • Now, click on enter to get the desired output

In console

java args1 args2 args3 …

 

As a result, we will get an output with these arguments, which we passed as an input. This program will print all these arguments separated by a new line:

args1
args2
args3 

 

As we can see, command-line arguments can only be of String type. What if we want to pass numbers as arguments? Let’s say you want to add something to the argument you pass. If you do it with the above program, it will be something like:

In the program

class test
{
    public static void main(String[] args)
    {
        for(int i=0;i< args.length;++i)
        {
            System.out.println(args[i]+1);
        }
    }
}

 

Check out upGrad’s Advanced Certification in DevOps 

In console

java test 11 12 13

 

Output

111
121
131

 

You can see that it appends the characters to the “String” of numbers. To add a number to them, we need to convert the arguments into integer form. To do so we use the parseInt() method of the Integer class. The implementation will be like –

In the program

class test {
    public static void main(String[] args) {
     for (int i = 0; i < args.length ; ++i ) {
     int arg = Integer.parseInt(args[i]);
     System.out.println(arg + 1);
     }
    }
}

 

In console

java test 11 12 13

 

Output

12
13
14

 

As you can see how we get our desired results. We can also do the same with double() and float() using parseDouble() and parseFloat().

Sometimes, the arguments that are provided cannot be turned into the specific numeric type, which will result in an exception called NumberFormatException.

Now you might think that we are passing these arguments to our application. Will it affect the performance of the application in any way? The answer to that is no. Passing arguments won’t slow down your application or have any other performance hits on it. Even if it does, it is very minimal and should not be noticeable.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

How to Calculate Factorial of Any Number through the Command-Line?

If you wish to use command line arguments in Java in different calculations, let’s first calculate the factorial of any number through the command-line argument:

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

 

Passing Numeric Command-Line Arguments in Java: Steps to Follow

It is noteworthy to state that the main() method of the Java program accesses data with string type arguments. So, you cannot pass numeric arguments through the command-line. If done so, they will be converted into the string. As a result, they cannot be used as numbers and fail to perform numeric operations. But there is one method to use them. Simply convert the string(numeric) arguments into the numeric values. Here’s the example:

public class NumericArguments
{
public static void main(String[] args)
{
     // convert into integer type
     int number1 = Integer.parseInt(args[0]);
        System.out.println("First Number: " +number1);
     int number2 = Integer.parseInt(args[1]);
     System.out.println("Second Number: " +number2);
     int result = number1 + number2;
        System.out.println("Addition of two numbers is: " +result);
}
}

 

In this program, you may use the parseInt()of the Integer class that converts the string argument into the integer.

Alternatively, you can also use the parseDouble() to convert the string into the double value or parseFloat()to convert it into the float value.

Read: Java Project Ideas & Topics

Variable Arguments in Java

In JDK 5, Java included a new feature that simplifies creating methods that need a variable number of arguments. This feature is called varargs which means variable-length-arguments. The method which takes the variable arguments is called a varargs method.

Before this feature had been implemented in Java, there were two possible ways to pass variable arguments in an application. One of them was using an overloaded method, and another involved passing the arguments in an Array and then passing that array to a method. Both of these methods were error-prone. Varargs solved all the problems that came with the previous methods with the added benefit of clean and less code to work with.

The variable-length-arguments are specified with three periods (…), below is the full syntax for the same –

public static void varMethod(int ... x) 
{
   // body of the method
}

 

The above syntax tells the compiler that varMethod() can be called with zero or more arguments.

Varargs can also be overloaded.

There are some rules for using varargs:

  • There can only be one variable argument in the method.
  • Variable arguments must be the last argument.

An Error Occurring on Using Two Arguments in a Varargs Method

void method(String... str, int... a)
{
    // Compile time error as there are two varargs
}

 

An Error Occurring When We Specify Varargs as the First Argument Instead of the Last One

void method(int... a, String str)
{
    // Compile time error as vararg appears 
    // before normal argument
}

 

So, if you want to pass variable arguments, you can use the varargs method.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Upskill, Upgrade and Update

Java is indeed an exceptional language and is being used by various multinational corporations and companies to develop large-scale applications. 

The scope for such skills can really upscale your career. upGrad has been providing exceptional courses in Machine Learning, Coding in many languages such as Java, C++, C, AI, Natural Language processing, and much more. Brighten up your career by upgrading to the language of the future: Java! 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. How to run a Java class using the command line?

2. What are jar files in Java?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program