Topics Index

Array - Overview >
Siva Nookala - 14 Mar 2016
Java supports command line arguments, which means you can pass parameters/arguments to the program. Depending upon the parameters passed to the program, it can be made to execute differently.

Pass Command Line Arguments
class CommandLineArguments
    public static void main(String args[])
        if(args.length == 0)
            System.out.println("Running the program with no arguments");
        else if(args.length == 1)
            System.out.println("Running the program with one argument - " + args[0]);
        else if(args.length == 2)
            System.out.println("Running the program with two argument - " + args[0] + " and " + args[1]);
            System.out.println("Invalid number of arguments only 0 or 1 or 2 arguments accepted.");

Running the program with no arguments


If we execute this program as 'java CommandLineArguments wqr SASS', then wqr and SASS will be considered as parameters. A String array containing these arguments will be created and passed to the main method. Since the name of the main method parameter is args, we can access these parameters using args[0] and args[1]. We can use args.length to get the number of parameters. In this case, it will be 2.
If we run the program using 'java CommandLineArguments 234', the number of arguments (args.length) will be 1 and it can be accessed using args[0]. Please note that although we are passing 234, which is integer, it is treated as String. If needed, we can convert this String into Integer using Integer.parseInt method.

  • Download this program locally and compile and run using the commands 'java CommandLineArguments', 'java CommandLineArguments 234', 'java CommandLineArguments wqr SASS' and 'java CommandLineArguments param1 param2 param3'. Observe that the output printed is different for different parameters.
Below image shows how the above program gives different output depending upon the arguments passed. Run-command-line-arguments-program
Below is an another example of command line arguments. Here we are taking only one argument and then printing that argument. If you run the following program using 'java EchoName Sachin', then it will print Hello Sachin. But if you run with out any arguments, then it throws an ArrayIndexOutOfBoundsException, since there is no element at the index 0.
class EchoName
    public static void main(String s[])
        System.out.println("Hello " + s[0]);

Dependent Topics : How to Compile and Run Java Program In Cmd Prompt 

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App