Programs

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.

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]);

        }

    }

}

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);

        }

    }

}

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.

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.

How 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.

What 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.

Want to share this article?

Land on Your Dream Job

Leave a comment

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

Contact Form

Our Popular Software Engineering Courses

Leave a comment

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

×
Let’s do it!
No, thanks.