Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconCommand Line Arguments in Java [With Example]

Command Line Arguments in Java [With Example]

Last updated:
23rd Jun, 2023
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Command Line Arguments in Java [With Example]

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:

Ads of upGrad blog
  • 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

Explore our Popular Software Engineering Courses

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.

Explore Our Software Development Free Courses

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.

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

Upskill, Upgrade and Update

Ads of upGrad blog

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

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

To run a Java class using command line i.e. from shell prompt simply type the command java -jar jar_file.jar where jar_file.jar is the name of your JAR file (e.g. QuoraAnswerManager.jar). The simplest way to run a Java class in the command line is to compile it and provide a classpath to it. Compile your Java class with the following command: javac -classpath classpathMainFolder myClass.java. Then run the compiled class with the following command: java -classpath classpathMainFolder myClass.

2What are jar files in Java?

In Java there are many types of jar files. Jar files are simply packages. The JAR file format was originally created for Java and was intended for software distribution. JAR files are sometimes called JAR archives because they function similarly to a ZIP file, in that they store multiple files and directories within a single file for easy distribution. A JAR file is sometimes referred to as a Java Archive. This is not technically correct, but is often used in the Java community where both the word archive and packaging are sometimes used to refer to JAR files.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43493
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229999
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon