Taking Command Line Arguments in Java

The command line argument is the argument which is passed at the time of running a Java application. Java can take any number of arguments from the command-line,  You could see that there will be String args[] used in the declaration of the main() method, which tells us that Java can takes all the argument which is passed in the command-line as String, but the question here is that how to pass the command-line argument to Java. 

Usually we will be running a Java program like below

java <<class name>>

Command line argument will be passed as an additional parameter while running

java <<class name>> <<parameter1>> <<parameter2>>

If we wish to pass a String array then we need to include the array as a simple string beside the class name, you can optionally add quotes as well but it is not required as Java takes all inputs as String only. Each parameter has to separated with a space. Both below inputs which is given below is valid

java Test one two tree

java Test "one" "two" "three"

The String arguments passed will be stored in the String args[] of the main() method, now args[] has three elements. These elements can be accessed in the normal way accessing a Java array.

Printing the command-line arguments

public class StringArrayExample 
    public static void main(String args[])
        for (int i =0;i<args.length;i++) 
            System.out.println("Parameter "+(i+1)+" : "+args[i]);

Upon execution we will be getting the below output

Parameter 1 : one
Parameter 2 : two
Parameter 3 : tree

Note :  The program displays each parameter in separate line. This is because the space character separates arguments. In order to have all of them to be considered as a single argument then we need to enclose them with a quotation like below

java StringArrayExample "one two three"

Then the output will be

Parameter 1 : one two three

Parsing Numeric Command-Line Arguments

Java program takes all the command line arguments as String by default but this will not help in all the cases. Suppose if your Java application needs to support numeric argument, then we need to parse the argument into integer.

public class Integer_Parse 
    public static void main(String args[])
        int value1,value2;
        if (args.length > 0) {
                value1 = Integer.parseInt(args[0]);
                value2 = Integer.parseInt(args[1]);
                System.out.println("Sum of parameters is : "+(value1+value2));
            catch (NumberFormatException e) 
                System.err.println("Argument passed is not integer");


java Integer_Parse 12 13

Sum of parameters is : 25

parseInt() method will throw NumberFormatException when the argument passed is not a valid Number type (float,int,double…)

Leave a Reply

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